CSE 207: AVL Trees: Dr. Md. Shamsuzzoha Bayzid
CSE 207: AVL Trees: Dr. Md. Shamsuzzoha Bayzid
20
21
log n
22
23
Binary Search Tree (BST)
The height may become larger than log2n
9
AVL Trees
Adelson-Velski and Landis, 1962
Dynamically rebalance the tree keeping the ordering invariant
Ordering Invariant
x
At any node with key k in a binary search tree, all keys
of the elements in the left subtree are strictly less than k,
while all keys of the elements in the right subtree are
strictly greater than k.
<x x
Height Invariant
10
4 16
1 7 13 19
14
15
A0 A1 A2 A3 A4
A1
A2
n(A0) = 1; n(A1) = 2;
n(Ah) = n(Ah-1) + n(Ah-2) + 1
AVL trees are balanced
n: 1 2 4 7 12
A0 A1 A2 A3 A4
1 2 4 7 12
1 1 2 3 5 8 13
Fibonacci Sequence
n(h) = f(h+2) -1
f(h) = O(ch)
c= (1+√5)/2
AVL: Rebalancing strategy
Prototypical example
7 4
4 Rotation 1 7
1
AVL: Rebalancing strategy
Prototypical example
Rotation may not work sometimes!
7 4
4 Rotation 7
5
1
AVL: Rebalancing strategy
Prototypical example
Rotation may not work sometimes!
7 4
4 Rotation 7
5
5
7
7
5
4 Rotation Rotation
5
4 7
5 4
AVL: Rebalancing
Rotation
x y
Rotation
y x
Rotation
C
A
C B B A
y≤B<x
AVL: Rebalancing
x y
y x
h/h+1
Rotation
h+2
h
C
h+2
h/h+1
h
C B B A
y≤B<x
At least one of B and C have height h+1, otherwise y cannot have height h+2
Since node y is height balanced, the other node has a height of h or h+1
Assume that h(C) = h+1 and h(B) = h/h+1. Does the rotation make it balanced?
Assume that h(B) = h+1 and h(C) = h/h+1. Does the rotation make it balanced?
AVL: Rotation
zig
x y
zi g
y x
h/h+1
Rotation
zi g
h+2
za
g
h
C
h+2
h/h+1
h
C B Rotation B A
Move downward from an unbalanced node, each time moving into the higher
subtree
See if it is zig-zig or zig-zag
Single rotation will suffice for zig-zig. Double rotation is needed for zig-zag
AVL: Double Rotation
Since B has height h+1, it is not empty. So we can expand it one more level
U and V has height h/h-1 (at least one of them has a height of h)
x x
zig
zi g
y y
Expand
za
za
g
g
h
h
h+2
h+2
A z A
h+1
h
h
C B C
h/h-1
U V
AVL: Double Rotation
x x
y z
Rotate at y
h
h+2
z A y A
h
C V
h/h-1
C U
U V
z C
Rotate at x
y x
h/h-1
h
h
C U V A
Practice