AVL Trees
AVL Trees
AVL tree
• Adelson-Velskii and Landis
• It is named after its inventors
• It is a self-balancing BST
• It is the first dynamically balancing tree
• The max difference between the height of left
and right sub-tree is 1(1,0,-1).
• It maintains O(log n) as running time for all
operations.
• It is not as perfectly balanced as red-black trees.
A BST is an AVL tree if:
• The sub-trees of every node differ in height by
at most one.
• Every sub-tree is an AVL tree.
Examples of BST : unbalanced BST
50
40 60
30 45
20 35
10 25
5 15
Examples of BST: left-skewed tree
50
40
30
20
10
5
Examples of BST: right-skewed tree
50
40
30
20
10
Balancing factor
Balancing factor=height of left subtree – height of right subtree {-1,0,1}
50
40 60
40
40
30 50 30 50
60 20
Find out the balancing factor of every node in all the three BST’s
Is this an AVL tree or not?
Rotations : LL
Insert 6 17
11
Rotations : RR
Insert 48
24
36
Rotations : LR
Insert 21
28
14
Rotations : RL
Insert 36
24
48
Insertion
21, 26, 30, 9, 4, 14, 28, 18, 15, 10, 2, 3, 7
Insertion
21, 26, 30, 9, 4, 14, 28, 18, 15, 10, 2, 3, 7
Insertion
21, 26, 30, 9, 4, 14, 28, 18, 15, 10, 2, 3, 7
Insertion
21, 26, 30, 9, 4, 14, 28, 18, 15, 10, 2, 3, 7
Insertion
21, 26, 30, 9, 4, 14, 28, 18, 15, 10, 2, 3, 7