AVL Trees
AVL Trees
AVL Trees
15
AVL Trees UMT 404 3
An AVL Tree
3 10 data
10 3 height
children
1 2
5 15
0 0 0 1
2 9 12 20
0 0
17 30
Insert(middle) M
Insert(small)
Insert(tall) 0 0
S T
h
h+1 b h-1 h a
X
h h-1 h-1
h-1 Z
Y Y X
Z
Height of left subtree same as it was before insert!
Height of all ancestors unchanged
We can stop here!
2 2
S S 1
M
1 1
T M
0 0
0 S T
0
M T
h-1 h-1
h-1 h
Z Y Z
h - 1?
h - 1?
Initially: insert into either X or Y unbalances tree (root balance goes to 2 or -2)
“Zig zag” to pull up c – restores root height to h+1, left subtree height to h
Done!
(There can only be one imbalance!)
1 2
5 15
0 0 0 1
2 9 12 20
0 0
17 30
2 2
5 15
1 0 0 1
2 9 12 20
0 0 0
3 17 30
2 3 2 2
5 15 5 20
1 0 0 2 1 0 1 1
2 9 12 20 2 9 15 30
0 0 1 0 0 0 0
3 17 30 3 12 17 33
0
33
AVL Trees UMT 404 18
Hard Insert (Bad Case #2)
3
Insert(18) 10
2 2
5 15
1 0 0 1
2 9 12 20
0 0 0
3 17 30
2 3 2 3
5 15 5 20
1 0 0 2 1 0 2 0
2 9 12 20 2 9 15 30
0 1 0 0 0 1
3 17 30 3 12 17
0 0
18 18
AVL Trees UMT 404 20
Double Rotation (Step #1)
3 3
10 10
2 3 2 3
5 15 5 15
1 0 0 2 1 0 0 2
2 9 12 20 2 9 12 17
0 1 0 0 1
3 17 30 3 20
0 0 0
18 Look familiar? 18 30
AVL Trees UMT 404 21
Double Rotation (Step #2)
3 3
10 10
2 3 2 2
5 15 5 17
1 0 0 2 1 0 1 1
2 9 12 17 2 9 15 20
0 1 0 0 0 0
3 20 3 12 18 30
0 0
18 30
AVL Trees UMT 404 22
AVL Insert Algorithm
Revisited
Recursive Iterative
1. Search downward for 1. Search downward for
spot, stacking
spot
parent nodes
2. Insert node 2. Insert node
3. Unwind stack, 3. Unwind stack,
correcting heights correcting heights
a. If imbalance #1, a. If imbalance #1,
single rotate single rotate and
exit
b. If imbalance #2,
b. If imbalance #2,
double rotate double rotate and
exit
a a First Rotation
b c
Z Z
c Y b
W
Y X X
W
AVL Trees UMT 404 25
Double Rotation
Completed
First Rotation Second Rotation
a c
c
a b
Z
Y b Y X
X Z W
2 2
5 15
1 0 0 1
2 9 12 20
0 0 0
3 17 30
2 2
5 15
1 0 0 1
2 9 12 20
0 0 0
3 17 30
2 2
5 17
1 0 0 1
2 9 12 20
0 0
3 30
2 2
5 17
1 0 0 1
2 9 12 20
0 0
3 30
2 2 2 1
5 17 5 20
1 0 1 1 0 0 0
2 9 20 2 9 17 30
0 0 0
3 30 3
2 3
5 17
1 0 2 2
2 9 12 20
0 0 1 0 1
3 11 15 18 30
0 0
13 33
AVL Trees UMT 404 32
Double Rotation on
Deletion
4 4 Not
10 10 finished!
2 3 1 3
5 17 3 17
1 2 2 0 0 2 2
2 12 20 2 5 12 20
0 0 1 0 1 0 1 0 1
3 11 15 18 30 11 15 18 30
0 0 0 0
13 33 13 33
AVL Trees UMT 404 33
Deletion with Propagation
4
10
What different about this case?
1 3
3 17
0 0 2 2
2 5 12 20
We get to choose whether
0 1 0 1 to single or double rotate!
11 15 18 30
0 0
13 33
3
17
5 8 10 15 2 2 20 30 35 40
10 35
5 8 1 0 20 30 1 0
8 15 30 40
0 0
5 20
i 1
T(n) = (n)