Professional Documents
Culture Documents
x
4 14
2 7 9
<x >x
1 3 12
Binary-search-tree property
For every node x
All keys in its left subtree are smaller than the key value in x
All keys in its right subtree are larger than the key value in x
Leaves: height = 0 2 2
4 14
Tree height = root height
1 0 1
Empty tree: height = −1 2 7 9
Question
Let n be the size of a binary search tree. How can we keep its
height O(log n) under insertion and deletion?
n0 = 1 n1 = 2 n2 = n1 + n0 + 1 = 4 n3 = n2 + n1 + 1 = 7
h 0 1 2 3 4 5 6 7 8
nh 1 2 4 7 12 20 33 54 88
fh 1 1 2 3 5 8 13 21 34
Lemma:
nh = fh+2 − 1
Proof: by induction
8 8 8
4 14 4 14 2 14
2 9 2 9 1 4 9
1
Insert 1 Restore height balance
After an insertion, only nodes that are on the path from the
insertion node to the root might have their balance altered
Because only those nodes have their subtrees altered
8 8
0 −1
4 14 4 14
−1 −1 −2 −1
2 9 2 9
0 0 −1 0
1
0
Insert 1
k+2 k+3
A A
−1 −2
B B
0 k −1 k
γ γ
k k k
α β k+1 α β
k+2 k+3
A A
1 2
B B
k 0 k 1
α α
k k k k+1
β γ β γ
k+2 k+3
A A
−1 −2
B B
0 k 1 k
γ γ
k k k k+1
α β α β
k+3
B
• Single rotation fails to fix it 2
A
• Subtree β is too tall k -1
α
k+1 k
β γ
A 2
−2 1
C
C
0
−1
B A
B 0 0
0
X X
0 δ −1 δ
k k
k−1
α α
β γ k−1 γ k−1
β k
A k+3
−2 k+2
X
X 0
−2 k B A
B 0 1
0 k−1
δ k−1
γ k
k γ
k
α β k δ
α β k
X X
0 δ 1 δ
k k
k−1
α α k−1
β γ k−1 β
k
γ
A k+3
−2 k+2
X
X 0
−1 k B A
B −1 0
−1 δ
k k−1
k−1 β
k k
k β γ
α γ k δ
α
2
1 A
A
2
1
B
B
−1
0
C
2 0
A
2
C 1
C
1
0
B A B
0 0 0
For each node along the path, restore the height balance if needed
by doing single or double rotations
Very similar to insertion with one major caveat
In insertion a (single/double) rotation restored balance and
kept height of rebalanced subtree unchanged.
⇒ Only one rotation needed.
In deletion, rotation restores balance but final height of rotated
subtree might decrease by one. If this occurs, need to continue
walking up path towards root, continuing to restoring balance
by rotations when necessary.
Since path has length O(h) this might require O(h) =
O(log n) rotations.
⇒ Deletion can also be done in O(log n) time.
k+3 B k+2
A
−1 0
B A 0
-1 k+1
γ
k+1
α
k+1 k k k
α β β γ
AVL trees are one particular type of Balanced Search trees, yielding
O(log n) behavior for dictionary operations.
There are many other types of Balanced Search Trees, e.g.
red-black trees
B-trees
(a, b) trees
(2, 3) and (2, 3, 4) trees are special cases
treaps (randomized BSTs)
splay Trees (only O(log n) in amortized sense)