Ds 12-AVL
Ds 12-AVL
Insertion
Deletion
Balance Binary Search Tree
Worst case height of binary search tree: N
Insertion, deletion can be O(N) in the worst case
We want a tree with small height
Height of a binary tree with N node is at least (log
N)
Goal: keep the height of a binary search tree O(log N)
Balanced binary search trees
Examples: AVL tree, red-black tree
Balanced Tree?
Suggestion 1: the left and right subtrees of root have the
same height
Suggestion 2: every node must have left and right
subtrees of the same height
Our choice: for each node, the height of the left and
right subtrees can differ at most 1,-1,0.
AVL Tree
An AVL (Adelson-Velskii and Landis 1962) 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.
N1=1, N2 =2 (base)
Nh= Nh-1 + Nh-2 +1 (recursive relation)
6 8
6
Insert 6
Original AVL tree Restore AVL property
Property violated
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
Different Rebalancing
Rotations
The rebalancing rotations are classified as LL, LR, RR
and RL as illustrated below, based on the position of
the inserted node with reference to α.
LL rotation: Inserted node is in the left subtree of the left
subtree of node α
RR rotation: Inserted node is in the right subtree of the
right subtree of node α
LR rotation: Inserted node is in the right subtree of the
left subtree of node α
RL rotation: Inserted node is in the left subtree of the
right subtree of node α
Insertion Analysis
Insert the new key as a new leaf just as in
ordinary binary search tree: O(logN)
Then trace the path from the new leaf towards
the root, for each node x encountered: O(logN)
Check height difference: O(1)
If satisfies AVL property, proceed to next node: O(1)
If not, perform a rotation: O(1)
The insertion stops when
A single rotation is performed logN
Or, we’ve checked all nodes in the path
Time complexity for insertion O(logN)
Basically follows deletion strategy of binary search tree
But may cause violation of AVL tree property
Restore the destroyed balance condition if needed
20 20
10 35 15 35
5 15 25 40 10 18 25 40
18 30 38 45 30 38 45
50 50
15 35 20 40
10 18 25 40 15 25 38 45
30 38 45 10 18 30 50