AVL Trees• Balanced binary search trees • For every node in an AVL tree, the heights of its left and right subtrees can differ by no more than 1... Balance Factors• Every node in an AVL
Trang 1AVL Trees
• Balanced binary search trees
• For every node in an AVL tree, the heights of its left and right subtrees can differ by no more than 1
N
N
N
Trang 2Balance Factors
• Every node in an AVL tree has a balance factor
• bfN = height(R) – height(L)
N
N
N
N
0
1
-1
Trang 3Balancing Operations
• Only insertion and deletion can affect balance
• All imbalances in an AVL tree involve some local three-node neighborhood and can be repaired within the confines of that neighborhood
A B C
Left rotation
B
A B C
Right rotation
B
A
B
C
A C B Left rotation
A
B
Left rotation
A C
Right rotation
C
Trang 4Balancing Operations
• Only insertion and deletion can affect balance
• All imbalances in an AVL tree involve some local three-node neighborhood and can be repaired within the confines of that neighborhood
5 10 15
Left rotation
10
15 10 5
Right rotation
10
5
15
10
5 10 15 Left rotation
15
5
10
Left rotation
15 10 5
Right rotation
10
Trang 5Subtree Displacement During Rotations
A
B
C
T1
T2
0 1 2
0
A
B
C
Left rotation
A C B
Right rotation T1
T4
T3
0
0
1
-2
Trang 6Building an AVL Tree
Insert: 10, 85, 15, 70, 20, 60, 30, 50, 65, 80, 90, 40, 5, 55
Insert 10
10
Insert 85
85 10
Insert 15
15 85
10
15 10
85
15
0 -1 2
Insert 70
15
70
Insert 20
15
70 20
15
0 -1 -2
Trang 7Insert 60
15
60
15
85
70 60
1
-1
2
15 10
20
85
70 60
Final Tree:
60
55
Trang 8Deleting from an AVL Tree
• After any insertion, at most one balancing repair would be needed (This may be a double rotation, but it’s just one repair.)
• After a deletion, there could be several repairs needed, but they will all be on the path from the deletion point to the root
60
55
Delete 70:
60
60
65
80
55
Delete 80:
60
65
55
1
-2
60
5
55 65
15
40
Trang 9Delete 20 from the following AVL Tree:
13
12
9
14
18
After two imbalance repairs (both double rotations):
8
13 5
16 11
7 3
18 15
12 10
4 1
6 2