Professional Documents
Culture Documents
AVL Tree
AVL Tree
(AVL Tree)
Dr.N.S.Nithya
ASP/CSE
AVL Tree
The AVL stands for Adelson-Velskii and
Landis, who are the inventors of the AVL
tree.AVL tree is a self-balancing binary
search tree in which heights of the left sub
trees and right sub trees of any node differ
by at most one.
Balancing Factor
Balance factor=height of left sub tree – height
of the right sub tree.
The value of balance factor should always be -
1, 0 or +1.
Need for height balanced trees
If the binary search tree is either left skewed or right
skewed(not balanced) , the searching time will be
increased. Because searching time depends upon the
height of the tree. h=log(n) where h is the height of
the tree and n is the number of nodes in the binary
tree.It takes log(n) for searching.
Balancing Factor Routine
int BF(node *T)
{
int lh,rh;
if(T==NULL)
return(0);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
return(lh-rh);
}
Need for height balanced trees
return(T);
}
node * RL(node *T) //insert right subtree of left
{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
Left Rotation
Right Rotation
Left-Right Rotation
Right-Left Rotation
Operations on an AVL Tree
4 -2 -1
Double rotation
1 -1 4
2 0 -1
0 6
0 -2 2
7 0 6 0
1 3 -1
0
1 3 15 0
5 16 5
0
0 16
Fig 13 0 7
15 Fig 14 0
Insert 14
-2 -1
4 4
Double rotation
0 0 0
-2
2 2 7
0 6 1 0
0 0 0
1 1 15
1 3 15 1 3 6
5
0 0 14 16
16 0
-1 7 0 5 0
Fig 15
14 0 Fig 16
Operations on an AVL Tree
T->ht=height(T);
return(T);
}
Deletion in AVL Trees
14
11 17
7 12 53
4 8 13
AVL Tree Example:
• Now remove 53, unbalanced
14
11 17
7 12
4 8 13
AVL Tree Example:
• Balanced! Remove 11(node with two children)
11
7 14
4 8 12 17
13
AVL Tree Example:
• Remove 11, replace it with the largest in its left branch
tree balanced
8
7 14
4 12 17
13
AVL Tree Example:
• Remove 8(place with inorder predessor)replace with
largest element in the left subtree, unbalanced
7
4 14
12 17
13
AVL Tree Example:
• Remove 8, unbalanced
4 12
14
13 17
AVL Tree Example:
• Balanced!!
12
7 14
4 13 17
node * Delete(node *T,int x)
{
node *p;
if(T==NULL)
{
return NULL;
}
else
if(x > T->data) // delete in right subtree
{
T->right=Delete(T->right,x);
if(BF(T)==2)
if(BF(T->left)>=0)
T=RR(T);
else
T=LR(T);
if(x<T->data)
{
T->left=Delete(T->left,x);
if(BF(T)==-2) //Rebalance
during windup
if(BF(T->right)<=0)
T=LL(T);
else
T=RL(T);
}
else
{
//data to be deleted is found
if(T->right!=NULL)
{ //delete its inorder succesor
p=p->right;
while(p->left!= NULL)
p=p->left;
T->data=p->data;
T->right=Delete(T->right,p->data);
15
15 24
20
10
24
13
20 20
13 24 15 24
10 15 13
10
15, 20, 24, 10, 13, 7, 30, 36, 25
20
13
13 24 10 20
10 15 7 15 24
7 30
13 36
10 20
7 15 30
24 36
15, 20, 24, 10, 13, 7, 30, 36, 25
13 13
10 20 10 20
7 15 30 7 15 24
24 36 30
25 13 25 36
10 24
7 20 30
15 25 36
Remove 24 and 20 from the AVL tree.
13 13
10 24 10 20
7 20 30 7 15 30
15 25 36 25 36
13 13
10 30 10 15
7 15 36 7 30
25 25 36