CSE 373: Data Structures and Algorithms: Lecture 10: AVL Trees
CSE 373: Data Structures and Algorithms: Lecture 10: AVL Trees
• buildTree
How can we make a BST efficient?
Observation
Structural properties
1. Binary tree property (same as BST)
2. Order property (same as for BST)
3. Balance condition:
balance of every node is between -1 and 1
where balance(node) =
height(node.left) – height(node.right)
4 8
1 7 11
10 12
Example #2: Is this an AVL Tree?
6
Balance Condition:
balance of every node is between -1 and 1
where balance(node) =
height(node.left) – height(node.right) 4 8
1 5 7 11
2
AVL Trees
Good News:
Because height of AVL tree is O(log(n)), then find
2 2
5 20
0 1 1 0
2 9 15 30
0 0
7 17
AVL tree operations
• AVL find:
• Same as usual BST find
• AVL insert:
• AVL delete:
• The “easy way” is lazy deletion
• Otherwise, do the deletion and then check for several imbalance cases (we will skip
this)
First insert example
Insert(6)
Insert(3)
Insert(1)
Third insertion
AVL Property 3
6
violated at node 6
3
1 6
1
Tree Rotations: Generalized
Generalizing our examples…
12
5 23
2 9 18 30
1 4 7 10
Generalizing our examples…
12
5 23
2 9 18 30
1 4 7 10
Generalizing our examples…
12
A C
Generalizing our examples…
12
d
A C
Generalized Single Rotation
A C
Generalized Single Rotation
C E
Single Rotations
2. For each node on the path from the root to the new leaf, the
insertion may (or may not) have changed the node’s height
E
A C
a’
15
8 22
4 10 19 24
3 6 17 20
16
Case #2:
15
15
8 24
8 22
24 4 10 22 25
4 10 19
3 6 3 6 19 23
23 25 26
26
Case #3:
right rotate
10 50
A) 42 B) 30 C) 50 D) 50
30 60 10 50 30 60 30 60
10 50 80 42 60 80 10 42 80 10 42 80
(Extra space for your scratch-work)
Practice time! Example of Case #4
10 50
41
AVL Tree Efficiency
left rotate
left rotate
right rotate