Professional Documents
Culture Documents
If number of nodes = 7
H eight(h) = log 2 7
Complexity = O( log 2 7 )
Complete Tree
The non-leaf node must have
a child node to the left.
Uses of Trees:
1. Tree Traversal
2. Represents a recursive data structure
2
Explanation for Tree Traversal:
1. Preorder:
Example:
PreOrder(TreeNode n)
process n.value(visit the rest)
preorder(n.left);
preorder(n.right);
Class TreeNode {
TreeNode left;
TreeNode right;
V value;
}
Example of pre-order:
Q
|
|-------------|--------|
| |
Z M
|
|-------------|-------------|
| |
X P
Output:
Q Z M X P
3
2. In-order
Example:
inOrder(TreeNode n)
inOrder(n.left);
process n.value(visit the rest)
inOrder(n.right);
Class TreeNode {
TreeNode left;
TreeNode right;
V value;
}
Example of In-order:
12
|
|-------------|--------|
| |
9 15
|-------------|
| |
7 10
Output:
7 9 10 12 15
4
3. Postorder
Example:
PostOrder(TreeNode n)
PostOrder(n.left);
PostOrder(n.right);
process n.value(visit the rest)
Class TreeNode {
TreeNode left;
TreeNode right;
V value;
}
Example of Post-order:
M
|
|-------------|--------|
No node |
Q
|
|
|--------|--------|
| |
X P
Output:
X P Q M
4. Level-order
5
More complicated, requires extra data structure such as queue/list to
create the necessary order
Example of In-order:
A
|
|-------------|--------|
| |
B C
|-------------|
| |
D E
Output:
A B C D E
Decision Trees
A tree whose node represents decision points, and whose children
represent the options available.
7
AddingElements
- Adding elements is similar to finding as element
- New elements are added as leaf nodes
- Start at the root, follow path directed by existing elements until you find no
child in the desired direction
- Then add new element
RemovinganElement
- After removing an element the resulting tree must still be valid
- Three distinct situation must be considered before removing an element
- The node to remove is a leaf
- The node to remove has one child
- The node to remove has two child
Case 1:
6
|------- |------- |
| |
3 9
|
|------- |
2 4
Remove(9)
Resulting tree:
6
|------- |------- |
| |
3 null
|
|------- |
2 4
8
Case 2:
6
|------- |------- |
| |
3 null
|
|
2
Remove(3)
6
|------- |------- |
| |
4 null
Example 2:
9
|
|
|----------------|----------------|
7 12
|
|----------------|----------------|
11 13
9
BalancingBSTs
A right rotation:
10