You are on page 1of 27

Chapter 6- AVL Trees

AVL Trees 6

6.1 What is an AVL tree?


6.2 Difference between Binary Search Tree and AVL Tree
6.3 Rotations
6.5 Key Terms
6.6 Review Questions

86
Chapter 6- AVL Trees

Objectives
In this chapter, we will discuss
AVL tree balance factor
Rotations of AVL trees
Pros and Cons of AVL trees

Introduction
Balancing Binary Search Trees
Many algorithms exist for keeping binary search trees balanced namely
 Adelson-Velskii and Landis (AVL) trees (height-balanced trees)
 Splay trees and other self-adjusting trees
 B-trees and other multiway search trees

6.1 AVL Trees

An AVL (Adelson-Velskii and Landis) tree is a binary search tree with a balance
condition. The balance condition must be easy to maintain, and it ensures that the depth of the
tree is O(log n). The simplest idea is to require that the left and right subtrees have the same
height.
An AVL tree is identical to a binary search tree, except that for every node in the tree, the
height of the left and right subtrees can differ by at most 1. (The height of an empty tree is
defined to be -1.) In Figure 6.1, the tree on the left is an AVL tree, but the tree on the right is not.

Figure 6.1 Two Binary Search Trees. Only The Left Tree Is AVL.

An AVL tree is a binary search tree in which every node is height balanced, that is, the
difference in the heights of its two subtrees is at most 1.

87
Chapter 6- AVL Trees

Balance Factor
The balance factor BF(T) of a node T is a binary tree is defined to be
B.F = hL – hR
where hL and hR respectively are the heights of the left and right sub trees of T(Tree).
or
The balance factor (BF) of a node is the height of its right subtree minus the height of its
left subtree.
An equivalent definition, then, for an AVL tree is that it is a binary search tree in which
each node has a balance factor of -1, 0, or +1. An AVL tree is a binary tree in which the
difference between the height of the right and left sub trees or the root node is never more than
one.

Figure 6.2 - Balancing Factor


Note:
 A balance factor of -1 means that the subtree is left-heavy, and a balance factor of +1
means that the subtree is right-heavy.
 For example, in the following figure 6.3 AVL tree, note that the root node with balance
factor +1 has a right subtree of height 1 more than the height of the left subtree. (The
balance factors are shown at the top of each node.)

Figure 6.3 - AVL tree


An AVL tree is a special type of binary tree that is always “partially” balanced. The
criteria that is used to determine the “level” of “balanced-tree” is the difference between the
heights of sub trees of a root in the tree. The “height of tree is the “number levels” in the tree.
To be more formal, the height of a tree is defined as follows:
1. The height of a tree with no elements is 0
2. The height of a tree with 1 element is 1

88
Chapter 6- AVL Trees

3. The height of tree with > 1 element is equal to 1 + height of its tallest sub tree
6.2 Difference between Binary Tree and AVL Tree

A binary tree is a tree data structure in which each node has at most two child nodes,
usually distinguished as "left" and "right". Nodes with children are parent nodes, and child nodes
may contain references to their parents. Outside the tree, there is often a reference to the "root"
node (the ancestor of all nodes), if it exists. Any node in the data structure can be reached by
starting at root node and repeatedly following references to either the left or right child. A tree
which does not have any node other than root node is called a null tree. In a binary tree, a degree
of every node is maximum two. A tree with n nodes has exactly n−1 branches or degree.
An AVL tree is a self-balancing binary search tree, and it was the first such data structure
to be invented. In an AVL tree, the heights of the two child subtrees of any node differ by at
most one; if at any time they differ by more than one, rebalancing is done to restore this property.
Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where
n is the number of nodes in the tree prior to the operation. Insertions and deletions may require
the tree to be rebalanced by one or more tree rotations.

Insertion of a Node
We can insert a new node into an AVL tree by first using binary tree insertion algorithm,
comparing the key of the new node with that in the root, and inserting the new node into the left
or right sub tree as appropriate.
It often turns out that the new node can be inserted without changing the height of a sub
tree, in which case neither the height not the balance of the root will be changed. Even when the
height of a subtree does increase, it may be the shorter subtree that has grown, so only the
balance factor of the root will change.

Insertions in AVL Trees


 Let the node that needs rebalancing be .
 There are 4 cases:
 Outside Cases (require single rotation):
1. Insertion into left subtree of left child of .
2. Insertion into right subtree of right child of .
 Inside Cases (require double rotation) :
3. Insertion into right subtree of left child of .
4. Insertion into left subtree of right child of .
 The rebalancing is performed through four separate rotation algorithms

89
Chapter 6- AVL Trees

AVL Rotations
A difference of levels between left and right subtrees can be increased, through insertion of a
new node into the tree, in 4 possible ways:
1. Insertion into left subtree of left branch. (Left-left case)
2. Insertion into right subtree of left branch. (Right-left case)
3. Insertion into left subtree of right branch. (Left-right case)
4. Insertion into right subtree of right branch. (Right-right case)
Rotations which reduce or correct the resulting imbalances are diagrammed for these 4 cases
below.
Note
 In the cases left-left and right –right, single rotation is applied after a new node is
inserted.
 In the cases right-left and left-right, double rotation is applied after a new node is
inserted.
CASE 1

Figure 6.4 - Single Rotation


Algorithm

void rot1(TOP *t){


NODE *k1,*k2=*t,*x,*y,*z;
k1=k2->left;
x=k1->left;
y=k1->right;
z=k2->right;
k1->right=k2;
k2->left=y;
set_level(k2);
set_level(k1);
*t=k1;
} 90
Chapter 6- AVL Trees

CASE 2

Figure 6.5 - Double Rotation

Algorithm
/*AVL rotation, type 2 */
void rot2(TOP *t)
{
NODE *k1,*k2,*k3=*t,*b,*c;
/* assign pointers to rotation object k1,
* and subtrees b and c */
k1=k3->left;
k2=k1->right;
b=k2->left;
c=k2->right;
/* perform rotation */
k1->right=b;
k3->left=c;
k2->left=k1;
k2->right=k3;
/* adjust k1,k3 and k2 levels */
set_level(k1);
set_level(k3);
set_level(k2);
/* replace t parameter in caller to reflect new subtree top */
*t=k2;
}
91
Chapter 6- AVL Trees

CASE 3
This case is symmetric with case 2.

Figure 6.6 - Double rotation

Algorithm

/*AVL rotation, type 3 */


void rot3(TOP *t)
{
NODE *k1=*t,*k2,*k3,*b,*c;
k3=k1->right;
k2=k3->left;
b=k2->left;
c=k2->right;
k1->right=b;
k3->left=c;
k2->left=k1;
k2->right=k3;
set_level(k1);
set_level(k3);
set_level(k2);
*t=k2;
}

92
Chapter 6- AVL Trees

CASE 4
This case is symmetric with case 1.

Figure 6.7 - Single rotation

Algorithm

/*AVL rotation, type 4 */


void rot4(TOP *t)
{
NODE *k1=*t,*k2,*x,*y,*z;
/* assign pointers to rotation object k1,
* and subtrees x,y and z*/
k2=k1->right;
x=k1->left;
y=k2->left;
z=k2->right;
/* perform rotation */
k1->right=y;
k2->left=k1;
/* adjust k1 and k2 levels */
set_level(k1);
set_level(k2);
/* replace t parameter in caller to reflect new subtree top */
*t=k2;
}
93
Chapter 6- AVL Trees

AVL Tree Right Rotations


These rotations are required when a node with balance factor -1 changes to -2 as a result
of a new node being inserted somewhere in it's left subtree. Change is needed at this node as it is
now out of balance. The tree is restored to an AVL tree by using a one of the right rotations.
A Single Right Rotation is used when the node that is out of balance to the left (balance
factor <= -2), and the left subtree is left heavy (balance factor = -1). This is sometimes called the
Left-Left case:

Figure 6.8 - Single Right Rotation

A Double Right Rotation is used when the node that is out of balance to the left
(balance factor <= -2), and the left subtree is right heavy (balance factor = 1). The double-right
rotation is a single-left rotation of the left subtree followed by a single right rotation of the node
that is out of balance. This is sometimes called the Left-Right case:

Figure 6.9 - Double Right Rotation

94
Chapter 6- AVL Trees

AVL Tree Left Rotations


These rotations are required when a node with balance factor 1 changes to 2 as a result of
a new node being inserted somewhere in its right subtree. Change is needed at this node as it is
now out of balance. The tree is restored to an AVL tree by using a one of the left rotations.
A Single Left Rotation for subtrees that are out of balance to the right (balance factor >=
2), and the right subtree is right heavy (balance factor = 1). This is sometimes called the Right-
Right case:

Figure 6.10 - Single Left Rotation

Double Left Rotation for subtrees that are out of balance to the right (balance factor >=
2) and the right subree is left heavy (balance factor = -1). The double-left rotation is a single-
right rotation of the right subtree followed by a single left rotation of the node that is out of
balance. This is sometimes called the Left-Right case:

Figure 6.11 - Double Left Rotation

6.3 Rotations of AVL Trees

95
Chapter 6- AVL Trees

When a new node has been inserted into the taller subtree of the root and its height has
increased, so that now one subtree has height 2 more than the other, and the tree no longer
satisfies the AVL requirements. We must now rebuild part of the tree to restore its balance.

The rebalancing can be carried out using four different kinds of rotations:
 LL
 RR
 LR &
 RL.
LL and RR are symmetric as are LR and RL. There rotations are characterized by the
nearest ancestor, A, of the inserted node, Y, whose balance factor become ± 2. The following
rotations type is obtained:
LL: New node Y is inserted in the Left Subtree of the Left Subtree of A (Single Rotation with
left)
LR: Y is inserted in the right subtree of the Left Subtree of A (Double Rotation with Left)
RR: Y is inserted in the right subtree of the right subtree of A (Single Rotation with Right)
RL: Y is inserted in the left subtree of the right subtree of A (Double Rotation with Right)

Rotations of AVL tree


1. Single Rotation
 Single Rotation with left - Left Rotation(Left of Left)
 Single Rotation with Right – Right Rotation(Right of Right)
2. Double Rotation
 Right – left Double Rotation
 Left-right Double Rotation

6.3.1 Single Rotation


6.3.1.1 Single Rotation with Left - Left Rotation(Left sub tree of left Child)

The two trees in Figure 6.11 contain the same elements and are both binary search trees.
First of all, in both trees k1 < k2. Second, all elements in the subtree X are smaller than k1 in
both trees. Third, all elements in subtree Z are larger than k2. Finally, all elements in subtree Y
are in between k1 and k2. The conversion of one of the above trees to the other is known as a
rotation. A rotation involves only a few pointer changes, and changes the structure of the tree
while preserving the search tree property.

96
Chapter 6- AVL Trees

Before Rotation After Rotation


Figure 6.12 - Single rotation
The rotation does not have to be done at the root of a tree; it can be done at any node in
the tree, since that node is the root of some subtree. It can transform either tree into the other.

From the above figure 6.12,


 The left child (K1) of the root (K2) is promoted as root node.
 The root (K2) is promoted as the right child of the new root(K1).
 The right child of the K1 is converted to the left child of K2

Routine to perform single rotation with left


1. This function can be called only if K2 has a left child.
2. Perform a rotation between node (K2) and its left child (K1)
3. Update height, then return new root.
static Position SingleRotateWithLeft (Position K2)
{
Position K1;
K1=K2 left;
K2 Left = K1 Right;
K1 Right =K2;
K2 height= Max (height(K2 left), height (K2 Right))+1;
K1 height= Max (height(K1 left), (K2 height))+1;
return K1;/*New Root*/
}
Example: the following tree which is balanced.

Figure 6.13 - Balanced tree


Now insert the value ‘1’ it becomes unbalanced due to insertion of the new node in the
Left Subtree of the Left Subtree. So we have to make single left rotation in the root node.
97
Chapter 6- AVL Trees

Figure 6.14 - Before Left Rotation

Figure 6.15 - After Left Rotation

6.3.1.2 Single Rotation With Right – Right Rotation(Right sub tree of Right Child)
 The right child(K2) of the root(K1) is promoted as root node.
 Its (K2) left child(Y) is converted to right child of the previous root node(K1).
 The previous root node(K1) is considered as the left child of new root node(K2).

Routine to Perform Single Rotation with Right:


1. This function can be called only if K1 has a right child.
2. Perform a rotation between node (K1) and its right child (K2)
3. Update height, then return new root.

Figure 6.16 - Single rotation with right

Algorithm

static Position SingleRotateWithRight (Position K1)


{
Position K2;
K2=K1 Right ;
98
K1 Right = K2 left;
K2 left =K1;
K2 height= Max (height(K2 left), height (K2 Right))+1;
Chapter 6- AVL Trees

Example
Consider the following tree which is balanced.

Figure 6.17 - Balanced Tree

Now insert the value ‘13’ it becomes unbalanced due to the insertion of new node in the Right
Subtree of the Right Subtree. So we have to make single Right rotation in the root node.

Figure 6.18 - Before Right Rotation

Figure 6.19 - After Right Rotation


6.3.2 Double Rotation
 Right – left Double Rotation

99
Chapter 6- AVL Trees

 Left-right Double Rotation

6.3.2.1 Right – Left Double Rotation


A double rotation, which is similar to a single rotation but involves four subtrees instead of
three. In Figure 6.20, the tree on the left is converted to the tree on the right. By the way, the
effect is the same as rotating between k1 and k2 and then between k2 and k3. There is a
symmetric case, which is also shown (see Fig. 4.34).

Figure 6.20 - (Right-left) double rotation


In our example, the double rotation is a right-left double rotation and involves 7, 15, and
14. Here, k3 is the node with key 7, k1 is the node with key 15, and k2 is the node with key 14.
Subtrees A, B, C, and D are all empty.

Figure 6.21 - (Left-right) double rotation

100
Chapter 6- AVL Trees

Figure 6.22- (Left-right) double rotation


Next we insert 13, which requires a double rotation. Here the double rotation is again a
right-left double rotation that will involve 6, 14, and 7 and will restore the tree. In this case, k3 is
the node with key 6, k1 is the node with key 14, and k2 is the node with key 7. Subtree A is the
tree rooted at the node with key 5, subtree B is the empty subtree that was originally the left child
of the node with key 7, subtree C is the tree rooted at the node with key 13, and finally, subtree D
is the tree rooted at the node with key 15.

Figure 6.23 - Double rotation (before inserting 13 and after inserting 13)
If 12 is now inserted, there is an imbalance at the root. Since 12 is not between 4 and 7,
we know that the single rotation will work.

101
Chapter 6- AVL Trees

Figure 6.24 - Double rotation (before inserting 12 and after inserting 12)
Insertion of 11 will require a single rotation

Figure 6.25 - Single rotation (before inserting 11 and after inserting 11)
Double Rotation with Left (Insertion in the Right Subtree of the Left Subtree - Left-Right
Rotation)

Before rotation After right rotation After left rotation


Figure 6.26 – Double Rotation with Left

Routine to perform double rotation with right and then Left


 Apply single Right rotation at K1, as a result K2 becomes the left child of the root node
K3 and K1 becomes the left child of K2.
 Apply single Left rotation at the root node K3, as a result K2 becomes the root node and
K1 becomes the left child of it and K3 becomes right child of it. Now the tree is balanced.

102
Chapter 6- AVL Trees

static Position DoubleRotateWithLeft (Position K3)


{
/* Rotate between K1 and K2*/
K3 Left = SingleRotateWithRight (K3 Left);
/* Rotate between K2 and K3*/
return SingleRotateWithLeft (K3);
}
Example
Consider the following tree which is balanced.

Figure 6.27 - Balanced Tree

Figure 6.28- Before Right Rotation


Now insert the value ‘12’& ‘18’ the tree becomes unbalanced due to the insertion of the
new node in the Right Subtree of the Left Subtree. So we have to make double rotation first with
right and then with Left.

Figure 6.29 - After Right Rotation & Before Left Rotation

103
Chapter 6- AVL Trees

Figure 6.30 - After Left Rotation

6.3.2.2 Double Rotation with Right(Insertion in the Left Subtree of the Right Subtree
Right-Left Rotation)
Routine to perform double rotation with right and then left
 Apply single Left rotation at K3, as a result K2 becomes the right child of the root node
K1 and K3 becomes the right child of K2.
 Apply single Right rotation at the root node K1, as a result K2 becomes the root node and
K1 becomes the left child of it and K3 becomes right child of it. Now the tree is balanced.

(a) (b) (c)


Figure 6.31 – (a) Before Rotation, (b) After Left Rotation, (c ) After Right Rotation

Algorithm

static Position DoubleRotateWithRight (Position K1)


{
/* Rotate between K2 and K3*/
K1 Right = SingleRotateWithLeft (K1 Right);
/* Rotate between K2 and K1*/
return SingleRotateWithRight (K1);
}

Example:

104
Chapter 6- AVL Trees

Consider the following tree which is balanced.

Figure 6.32 - Balanced Tree

Figure 6.33 - Before Left Rotation

Figure 6.34 - After Left Rotation & Before Right Rotation

Figure 6.35 - After Right Rotation

Algorithm

105
Chapter 6- AVL Trees

//Find height of a node

static int height (Position P)


{
if (P= =NULL)
return -1;
else
return P height;
}

Declaration for AVL tree


struct AvlNode
{
DataType data;
AvlTree Left;
AvlTree Right;
int height;
};

Algorithm
// Insert a node in the AVL Tree

AvlTree Insert (DataType X, AvlTree T)


{
if(T= =NULL)
{
T=malloc(size of (struct AvlNode))/*create one node tree*/
if (T= =NULL)
Fatalerror(“out of space);
else
{
T ->data =X;
T ->height=0;
T ->Left = T ->Right = NULL;
}
}
else
if (X<T-> data)
{
T ->Left = Insert(X,T-> Left);
if (height(T Left)
106- height(T Right)= =2)
{
if (X<T->Left data)
T=SingleRotateWithLeft(T);
Chapter 6- AVL Trees

else
if(X>T-> data)
{
T Right=Insert(X,T-> Right);
if (height(T Right)-height(T-> Left)= =2)
{
if (X>T-> Right data)
T=SingleRotateWithRight(T);
else
T=DoubleRotateWithRight(T);
}
/else X is in tree already. We will do nothing*/;
T height =Max(height(T-> Left), height(T-> Right))+1;
return T;
}

Example
Let us consider how to balance a tree while inserting the numbers 20, 10, 40, 50, 90, 30, 60, 70.
Step 1:(Insert the value 20)

Step 2: (Insert the value 10)

Step 3: (Insert the value 40)

107
Chapter 6- AVL Trees

Step 4:(Insert the value 50)

Step 5: (Insert the value 90)

Now the tree is unbalanced due to the insertion of node in the Right subtree of the Right
subtree. So we have to make single Right rotation in the node ‘40’

After the Right Rotation:


Now the tree is balanced.
Step 6: (Insert the value 30)

Now the tree is unbalanced due to the insertion of node’30’ in the Left subtree of the
Right subtree. So we have to make Double rotation first with Left on the node ‘50’ and then with
Right on the node ‘20’.

108
Chapter 6- AVL Trees

After Left Rotation

After Right Rotation


Now the tree is balanced
Step 7: (Insert the value 60)

Now the tree at the node ‘50’is unbalanced due to the insertion of node ‘60’ in the Left
subtree of the Right subtree. So we have to make Double rotation first with Left on the node ‘90’
and then with Right on the node ‘50’.

After Left Rotation

109
Chapter 6- AVL Trees

After Right Rotation


Now the tree is balanced.
Step 8: (Insert the value 70)

The tree is balanced.

Pros and Cons of AVL Trees


Arguments for AVL trees
1. Search is O(log N) since AVL trees are always balanced.
2. Insertion and deletions are also O(logn)
3. The height balancing adds no more than a constant factor to the speed of insertion.

Arguments against using AVL trees


1. Difficult to program & debug; more space for balance factor.
2. Asymptotically faster but rebalancing costs time.
3. Most large searches are done in database systems on disk and use other structures (e.g. B-
trees).
4. Longer running times for the insert and remove operations

6.4 Summary

An AVL (Adelson-Velskii and Landis) tree is a binary search tree with a balance
condition. The balance condition must be easy to maintain, and it ensures that the depth of the
tree is O(log n). The simplest idea is to require that the left and right subtrees have the same
height.

110
Chapter 6- AVL Trees

An AVL tree is identical to a binary search tree, except that for every node in the tree, the
height of the left and right subtrees can differ by at most 1. (The height of an empty tree is
defined to be -1.)
AVL trees work by insisting that all nodes' left and right subtrees differ in heights by at
most one. This ensures that the tree cannot get too deep. The operations that do not change the
tree, as insertion does, can all use the standard binary search tree code. Operations that change
the tree must restore the tree. This can be somewhat complicated, especially in the case of
deletion.

6.5 Key Terms

AVL trees, Balance factor


Rotations
Single rotations
Double rotations
Right-left Double Rotation
Left-right Double Rotation
Single Rotation with left - Left Rotation
Single Rotation with Right– Right Rotation

6.6 Review Questions

Two Mark Questions


1. Define AVL tree
2. Define Balancing factor.
3. What are the various transformation performed in AVL tree?
4. Define single rotation.
5. Define double rotation.
6. Write a routine to perform single rotation in AVL trees.
7. Write a routine to perform double rotation in AVL trees.
8. Show the result of inserting 2, 1, 4, 5, 9, 3, 6, 7 into an initially empty AVL tree.
9. List out the applications of AVL trees.
Big Questions
1. Define AVL trees? Explain the LL, RR, RL, LR case with an example.
2. Discuss various rotations of AVL tree in brief.
3. Discuss single rotation with its routine in brief.
4. Explain in detail about insertion into AVL Trees
5. Explain double rotation with its routine in detail.

111
Chapter 6- AVL Trees

Exercises
1. Show the result of inserting the following words into the AVL tree: Madhushri, Kanchan,
Anagha, Rohit, Neeta, Snehal, Pratibha, Lalitha, Mrudul, Kavitha, Apurva, Harsha.
2. What is the minimum number of nodes in an AVL tree of height 15?
3. Write a nonrecursive function to insert into an AVL tree.
4. Show the result of inserting the numbers from 1 to 10 into an initially empty AVL tree.

112

You might also like