csc2001f 2024 7 Avl Trees
csc2001f 2024 7 Avl Trees
2024
(Based on slides from Hussein Suleman; Additional content from
Sedgewick Algorithms in Java)
AVL Trees
To improve the worst case time complexity of BST
operations, the nodes should be arranged to minimize
the height of the tree
A complete or perfect tree would be ideal, but this
is too restrictive: instead we aim for a balanced tree
An AVL (Adelson-Velskii and Landis) Tree is a Binary
Search Tree with an additional balance property:
For every node in the tree, the heights of the left
and right sub-trees are at most different by 1
department of computer science
AVL Trees
Modify insert and delete operations to ensure the tree
stays balanced
3 7
1 4 6 9
3 7
1 6 9
0 2
3 7
1 4 6 9
2 8
Auxiliary routines:
manage height: precalculate it; fix it after changes
rebalance
rotate left/right
Double rotations:
insertion into right subtree of left child
insertion into left subtree of right child
department of computer science
Single rotation: rotateWithLeftChild
12
10
10
12
C
H-3
A
H-2
A B
B C
H-2 H-3
Initial height: H
12
10
A
H-3
C
H-2
B
C A
B
H-2 H-3
Initial height: H
3 7
1 12
5
1 4
A 11 10
C
H-3
B A B
C
H-3 H-3 H-3
department of computer science
Double rotation: doubleRotateWithLeftChild 2
12
11
11 second rotate right
D
H-3
10 12
10
C
A B D
C
A B H-3 H-3 H-3
H-3 H-3
department of computer science
Double rotation: doubleRotateWithRightChild
1
10 10
Initial height: H first rotation right
A 12 A 11
H-3 H-3
11 B 12
D
H-3 H-3
B D
C C H-3
H-3
department of computer science
Double rotation: doubleRotateWithRightChild
2
10
11
second rotate left
A 11
H-3
10 12
B 12
H-3
A B D
C
D H-3 H-3 H-3
C H-3
2 5
2 7 4 7
1 4 2
1 3 7
3 1 3