Data Structure
Data Structure
Fall 2006
Lecture 17-18
AVL Trees / Slide 2
Balanced Tree?
Suggestion 1: the left and right subtrees of
root have the same height
But the left and right subtrees may be linear lists!
Suggestion 2: every node must have left and
right subtrees of the same height
Only complete binary trees satisfy
Too rigid to be useful
Our choice: for each node, the height of the
left and right subtrees can differ at most 1
AVL Trees / Slide 4
AVL Tree
An AVL tree is a binary search tree in which
for every node in the tree, the height of the left and
right subtrees differ by at most 1.
Height of subtree: Max # of edges to a leaf
Height of an empty subtree: -1
Height of one node: 0
AVL tree AVL property
violated here
AVL Trees / Slide 5
N0 = 1 N1 = 2 N2 =4 N3 = N1+N2+1=7
height of left=?
Height right=?
AVL Trees / Slide 6
N0=0, N1 =2 (base)
Nh= Nh-1 + Nh-2 +1 (recursive relation)
6 8
6
Insert 6
Original AVL tree Restore AVL property
Property violated
AVL Trees / Slide 9
Some Observations
After an insertion, only nodes that are on the path
from the insertion point to the root might have their
balance altered
Because only those nodes have their subtrees altered
Rebalance the tree at the deepest such node
guarantees that the entire tree satisfies the AVL
property
6 8
6
Node 5,8,7 might Rebalance node 7
have balance altered guarantees the whole tree be AVL
AVL Trees / Slide 10
Rotations
Rebalance of AVL tree are done with simple
modification to tree, known as rotation
Insertion occurs on the “outside” (i.e., left-left
or right-right) is fixed by single rotation of the
tree
Insertion occurs on the “inside” (i.e., left-right
or right-left) is fixed by double rotation of the
tree
AVL Trees / Slide 12
Insertion Algorithm
First, insert the new key as a new leaf just as in
ordinary binary search tree
Then trace the path from the new leaf towards
the root. For each node x encountered, check if
heights of left(x) and right(x) differ by at most 1
If yes, proceed to parent(x)
If not, restructure by doing either a single rotation or
a double rotation
Note: once we perform a rotation at a node x,
we won’t need to perform any rotation at any
ancestor of x.
AVL Trees / Slide 13
k2 violates
AVL-property quiz:
1. Can Y have the same height as the new X?
2. Can Y have the same height as Z?
AVL Trees / Slide 14
k2 k1
k1 X k2
X
AVL Trees / Slide 15
k1 violates
An insertion in subtree Z
4 4
2 5 2 6
1 3 6 1 3 5 7
Insert 7,
violation at node 5 7 Single rotation
4
4
2 6
2 6
What is the result?
1 3 5
1 3 5 7
Single rotation
Insert 16, fine 16 But….
Insert 15
Violation remains
violation at node 7 15
AVL Trees / Slide 18