AVL Trees Lect
AVL Trees Lect
• binary tree
• for every node x, define its balance factor
balance factor of x = height of left subtree of x
– height of right subtree of x
• balance factor of every node x is – 1, 0, or 1
AVL Tree
Balance Factors
0
1 0
0 0 -1
0
0
0 0 0 0
7 40
45
3 8 30
35 60
1 5 20
25
Example AVL Tree
-1
10
1 1
7 40
0 1 -1
0 45
3 8 30
0
0 0 -1 0 60
35
1 5 20
0
25
put(9)
-1
10
0 1 1
7 40
0 1 -1
0 -1 45
3 8 30
0
0 0 0 -1 0 60
35
1 5 9 20
0
25
put(29)
-1
10
1 1
7 40
0 1 -1
0 45
3 8 30
0
0 0 -2 -1 35
0 60
1 5 20
0 -1
RR imbalance => new node is in 25
right subtree of right subtree of 0
1 1
7 40
0 1 -1
0 45
3 8 30
0
0 0 0 0 60
35
1 5 25
0 0
20 29
RR rotation.
Imbalance Types
10 20 10 30
20 10
LR Rotation
n 10 n 10 n 20
30 10
20 30
20 30
LL Rotation
n 30
temp 20
tl 10 25 tr
temp 20
tl n
10 30
25 tr
RR Rotation
n 10
20 temp
tl 15 25 tr
temp 20
tr
n 10 25
tl 15
Insert Node
Remove An Element
-1
10
1 1
7 40
0 1 -1
0 45
3 8 30
0
0 0 -1 0 60
35
1 5 20
0
25
Remove 8.
Remove An Element
-1
10
2 q 1
7 40
0 1 -1
45
3 30
0
0 0 -1 0 60
35
1 5 20
0
• Let q be parent of deleted node.25
• Retrace path from q towards root.