Intro To Trees-02AVL

You might also like

You are on page 1of 16

AVL tree

 Height balance tree

 G.M ADEL ‘SON-VELSKII and E.M LANDIS


 AVL tree is a binary search tree in which the heights
of the left and right subtrees of the root differ by at
most 1 and in which the left and right subtrees are
again AVL trees.
AVL tree

 A node in a binary tree has the AVL property if the height


of the left and right subtrees differ by at most one.
 If every node in the tree has the AVL property then the
tree is said to be an AVL tree.
Height Balanced

 HB: Height Balancing Factor i.e. Difference b/w


height of the Left subtree and right subtree
 HB=0
 HB=1
 HB=-1
Balancing

8
10

10
8 12

12
Height Balanced Trees

HB=-2 0 -1 -1
Insertion into AVL Trees

 After an insertion only nodes on the path from the insertion point
to the root can have had their balances altered

 The node that requires rebalancing is X

 There are 4 possible cases which caused the imbalance:


1) An insertion in the left subtree of the left child of X
2) An insertion in the right subtree of the left child of X
3) An insertion in the left subtree of the right child of X
4) An insertion in the right subtree of the right child of X

 1 and 4 are mirror images as are 2 and 3


Insertion into AVL Trees

 Correct balance using rotations

 Case 1 and 4 by single rotation, case 2 and 3 by a


double rotation.

 Rotation restores local balance and tree is once more


AVL
C B
B
A C
A Single Right Rotate
from B to C
SLR
Single Rotation Left

K1
K2
K2
A h+2
B
C

K2

K1 h+1
C
A
A B
SRR
Double Rotation

 The single rotation cannot solve the position of cases 2 and 3:


 The single rotation does not make the subtree that has caused
the imbalance any less deep
 Need to consider more detail of local tree structure
 What is required is a double rotation involving 3 nodes and 4
subtrees.
 The double rotation is effectively 2 single rotations:

1) one about the parent, and a


2) second single rotation about the grandparent.
DRR
K3
K1
K2
D
A
B C

K2
K1 K3

A B C D
DLR
Example of AVL

You might also like