Professional Documents
Culture Documents
09 Binary Trees
09 Binary Trees
Every node in the binary tree is reachable from the root node by a
unique path
a
b
d
g
e
h
f
i
l
3
Left Right
A
B
In the first binary tree, node A has a left child but no right child;
in the second, node A has a right child but no left child
Put another way: Left and right are not relative terms
More terminology
b
d
is at depth zero
e is at depth 2
a
Balance
a
b
d
c
e
b
c
h i
j
A balanced binary tree
e
f
i j
An unbalanced binary tree
A binary tree is balanced if every level above the lowest is full (contains
2n nodes)
In most applications, a reasonably balanced binary tree is desirable
7
15
12
20
17
0 1
2 3
lo = 2;
(2+2)/2=2
Using a binary
search tree
7
3
7 11 13 17
13
5
11 17
9
Tree traversals
10
class BinaryTree
class BinaryTree<V> {
V value;
BinaryTree<V> leftChild;
BinaryTree<V> rightChild;
// Assorted methods
}
11
Preorder traversal
12
Inorder traversal
13
Postorder traversal
14
preorder
inorder
postorder
C
E
ABDECFG
B
G
C
E
D B EAF C G
C
E
DEBFGCA
15
16
Other traversals
That is, the right subtree is traversed before the left subtree
is traversed
18
The End
19