Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Taiz University

Al-saeed Faculty for Engineering


and Information Technology
Information Technology Department

Data Structure and Algorithms II

Lecture 7

AVL Trees

Done By
BASHAR ABDULQAWI QASSEM
(IT)

Supervisor
Eng. Salah Alssayany

2023
Data Structures II AVL Trees

In this Algorithm tutorial, we will learn:

 What are AVL Trees?


 How does AVL Tree work?
 Balance Factor in AVL Trees
 Properties of Balance Factor
 AVL Rotations
 Left – Left Rotation
 Right – Right Rotation
 Right – Left Rotation
 Left – Right Rotation
 Operations on an AVL Tree
 Search in AVL Trees
 Insertion in AVL Trees
 Deletion in AVL Trees
 C++ Example of AVL Trees
 Advantages of AVL Trees
 Summary

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

What are AVL Trees?


AVL tree is a height-balanced binary search tree. That means, an AVL tree is
also a binary search tree but it is a balanced tree. A binary tree is said to be
balanced if, the difference between the heights of left and right subtrees of
every node in the tree is either -1, 0 or +1. In other words, a binary tree is said
to be balanced if the height of left and right children of every node differ by
either -1, 0 or +1. In an AVL tree, every node maintains an extra information
known as balance factor. The AVL tree was introduced in the year 1962 by
G.M. Adelson-Velsky and E.M. Landis.

An AVL tree is defined as follows...

An AVL tree is a balanced binary search tree. In an AVL tree, balance factor of
every node is either -1, 0 or +1.

How does AVL Tree work?


To better understand the need for AVL trees, let us look at some
disadvantages of simple binary search trees.

Consider the following keys inserted in the given order in the binary
search tree.

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

The height of the tree grows linearly in size when we insert the
keys in increasing order of their value. Thus, the search operation,
at worst, takes O(n).

It takes linear time to search for an element; hence there is no use


of using the Binary Search Tree structure. On the other hand, if the
height of the tree is balanced, we get better searching time.

Let us now look at the same keys but inserted in a different order.

Search takes O(log n)

Height Balanced

Here, the keys are the same, but since they are inserted in
a different order, they take different positions, and the
height of the tree remains balanced. Hence search will not
take more than O(log n) for any element of the tree. It is
now evident that if insertion is done correctly, the tree’s
height can be kept balanced.

In AVL trees, we keep a check on the height of the tree


during insertion operation. Modifications are made to
maintain the balanced height without violating the
fundamental properties of Binary Search Tree.

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

Balance Factor in AVL Trees


Balance factor (BF) of a node is the difference between the heights of
the left and right subtrees of that node. The balance factor of a node is
calculated by height of left subtree - height of right subtree. In the
following explanation, we calculate as follows…
Balance factor (BF)= height(Left_Subtree) – height(Right_Subtree)

Properties of Balance Factor

Balance factor AVL tree

 The balance factor is known as the difference


between the height of the left subtree and the right
subtree.
 Balance factor(node) = height(node->left) –
height(node->right)
 Allowed values of BF are –1, 0, and +1.
 The value –1 indicates that the right sub-tree
contains one extra, i.e., the tree is right heavy.
 The value +1 indicates that the left sub-tree contains
one extra, i.e., the tree is left heavy.
 The value 0 shows that the tree includes equal nodes
on each side, i.e., the tree is perfectly balanced.

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

Example of AVL Tree


This tree is a
binary search tree
and every node is
satisfying balance
factor condition.
So this tree is said
to be an AVL tree.

 Every AVL Tree is a binary search tree but every Binary


Search Tree need not be AVL tree.

If the balance factor of any node in an AVL tree becomes less than
-1 or greater than 1, the tree has to be balanced by making a
simple modifications in the tree called rotation.

An AVL tree causes imbalance, when any one of the following


conditions occur. α – is the node must be rebalanced.
Case 1: An insertion from the left sub tree of the left child of node α.
Case 2: An insertion into the right sub tree of the right child of α.
Case 3: An insertion into the left sub tree of the right child of α.
Case 4: An insertion into the right sub tree of the left child of α.

These imbalances can be overcome by


i. Single Rotation
ii. Double Rotation

Case 1 and Case 2 imbalance (left – left or right – right) is fixed by


a single rotation of the tree. Case 3 and Case 4 imbalance (left – right or
right – left) is fixed by double rotation.

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

AVL Rotations
In AVL tree, after performing operations like insertion and
deletion we need to check the balance factor of every node
in the tree. If every node satisfies the balance factor
condition then we conclude the operation otherwise we
must make it balanced. Whenever the tree becomes
imbalanced due to any operation we
use rotation operations to make the tree balanced.

Rotation operations are used to make the tree balanced.

Rotation is the process of moving nodes either to left or to right to make


the tree balanced.

There are four rotations and they are classified into two types.

 Left – Left Rotation


 Right – Right Rotation
 Right – Left Rotation
 Left – Right Rotation

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

Single Rotation
 Left - Left Rotation (LL Rotation)
In LL Rotation, every node moves one position to right from the current position. To
understand LL Rotation, let us consider the following insertion operation in AVL Tree...

This rotation is performed when a new node is inserted at the left


child of the left subtree.

AVL Tree Left – Left Rotation

This type of rotation is identified when a node has a balanced factor


as +2, and its left-child has a balance factor as +1.

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

 Right - Right Rotation (RR Rotation)


In RR Rotation, every node moves one position to right from the current position. To
understand RR Rotation, let us consider the following insertion operation in AVL Tree...

This rotation is performed when a new node is inserted at the right


child of the right subtree.

This type of rotation is identified when a node has a balanced factor

as -2, and its right-child has a balance factor as -1.

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

Double Rotation
 Left Right Rotation (LR Rotation)
The LR Rotation is a sequence of single left rotation followed by a single right rotation. In
LR Rotation, at first, every node moves one position to the left and one position to right
from the current position. To understand LR Rotation, let us consider the following insertion
operation in AVL Tree...

This rotation is performed when a new node is inserted at the left child of the right
subtree.

This rotation is performed when a node has a balance factor as +2,


and its left-child has a balance factor as -1.

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

 Right Left Rotation (RL Rotation)


The RL Rotation is sequence of single right rotation followed by single left rotation. In RL
Rotation, at first every node moves one position to right and one position to left from the
current position. To understand RL Rotation, let us consider the following insertion
operation in AVL Tree...

This rotation is performed when a new node is inserted at the right


child of the left subtree.

This rotation is performed when a node has a balance factor as –2,


and its right-child has a balance factor as +1.

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

Operations on an AVL Tree


The following operations are performed on AVL tree...

1. Search
2. Insertion
3. Deletion

 Search Operation in AVL Tree


In an AVL tree, the search operation is performed with O(log n) time complexity. The
search operation in the AVL tree is similar to the search operation in a Binary search tree.
We use the following steps to search an element in AVL tree...

 Step 1 - Read the search element from the user.


 Step 2 - Compare the search element with the value of root node in the tree.
 Step 3 - If both are matched, then display "Given node is found!!!" and terminate
the function
 Step 4 - If both are not matched, then check whether search element is smaller or
larger than that node value.
 Step 5 - If search element is smaller, then continue the search process in left
subtree.
 Step 6 - If search element is larger, then continue the search process in right
subtree.
 Step 7 - Repeat the same until we find the exact element or until the search
element is compared with the leaf node.
 Step 8 - If we reach to the node having the value equal to the search value, then
display "Element is found" and terminate the function.
 Step 9 - If we reach to the leaf node and if it is also not matched with the search
element, then display "Element is not found" and terminate the function.

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

 Insertion Operation in AVL Tree


In an AVL tree, the insertion operation is performed with O(log n) time complexity. Insert
operation is almost the same as in simple binary search trees. After every insertion, we
balance the height of the tree. In AVL Tree, a new node is always inserted as a leaf node.
The insertion operation is performed as follows...

 Step 1 - Insert the new element into the tree using Binary Search Tree insertion
logic.
 Step 2 - After insertion, check the Balance Factor of every node.
 Step 3 - If the Balance Factor of every node is 0 or 1 or -1 then go for next
operation.
 Step 4 - If the Balance Factor of any node is other than 0 or 1 or -1 then that tree
is said to be imbalanced. In this case, perform suitable Rotation to make it
balanced and go for next operation.

Example: Construct an AVL Tree by inserting


numbers from 1 to 8.

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

RR Rotation at 1

RR Rotation at 3

RR Rotation at 5

RR Rotation at 5

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

 Deletion Operation in AVL Tree


The deletion operation in AVL Tree is similar to deletion operation in BST. But after every
deletion operation, we need to check with the Balance Factor condition. If the tree is
balanced after deletion go for next operation otherwise perform suitable rotation to make
the tree Balanced.

Advantages of AVL Trees


 The height of the AVL tree is always balanced. The height
never grows beyond log N, where N is the total number of
nodes in the tree.
 It gives better search time complexity when compared to
simple Binary Search trees.
 AVL trees have self-balancing capabilities.

 Summary:
 AVL trees are self-balancing binary search trees.
 Balance factor is the fundamental attribute of AVL trees
 The balance factor of a node is defined as the difference
between the height of the left and right subtree of that node.
 The valid values of the balance factor are -1, 0, and +1.
 The insert and delete operation require rotations to be
performed after violating the balance factor.
 The time complexity of insert, delete, and search operation is
O(log N).
 AVL trees follow all properties of Binary Search Trees.
 The left subtree has nodes that are lesser than the root node.
The right subtree has nodes that are always greater than the
root node.
 AVL trees are used where search operation is more frequent
compared to insert and delete operations.

C++ Code of AVL Trees

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

#include<iostream> int AVL_tree::height(AVL *t) { parent->l = RR_Rotation (t);

using namespace std; int h = 0; cout<<"\n ==> Left-Right


Rotation (LR) <==";
struct AVL { if (t != NULL) {
return LL_Rotation (parent);
int d; int l_height = height(t->l);
}
struct AVL *l; int r_height = height(t->r);
AVL *AVL_tree::RL_Rotation (AVL
struct AVL *r; int max_height = max(l_height, *parent) {
r_height);
}*r; AVL *t;
h = max_height + 1;
class AVL_tree { t = parent->r;
}
public: parent->r = LL_Rotation (t);
return h;
int height(AVL *); cout<<"\n ==> Right-Left
} Rotation (RL) <==";
int difference(AVL *);
int AVL_tree::difference(AVL *t) { return RR_Rotation (parent);
AVL *RR_Rotation (AVL *);
int l_height = height(t->l); }
AVL *LL_Rotation (AVL *);
int r_height = height(t->r); AVL *AVL_tree::balance(AVL *t) {
AVL *LR_Rotation (AVL*);
int b_factor = l_height - r_height; int bal_factor = difference(t);
AVL *RL_Rotation (AVL *);
return b_factor; if (bal_factor > 1)
AVL * balance(AVL *);
} {
AVL * insert(AVL*, int);
AVL *AVL_tree::RR_Rotation (AVL if (difference(t->l) > 0)
void show(AVL*, int); *parent) {
t = LL_Rotation (t);
void inorder(AVL *); AVL *t;
else
void preorder(AVL *); t = parent->r;
t = LR_Rotation (t);
void postorder(AVL*); parent->r = t->l;
}
AVL_tree() { t->l = parent;
else if (bal_factor < -1) {
r = NULL; cout<<"\n ==> Right-Right
Rotation (RR) <=="; if (difference(t->r) > 0)
}
return t; t = RL_Rotation (t);
‫دالة لطباعة الشجرة بتنسيق منظم على‬//
)‫شكل شجرة (ليس له عالقة بموضوع الدرس‬ } else
void printTree(AVL* root, string AVL *AVL_tree::LL_Rotation (AVL t = RR_Rotation (t);
indent, bool last) *parent) {
}
{if (root == NULL) AVL *t;
{return;} return t;
t = parent->l;
printTree(root->r, }
indent + (last ? " | " : " "), parent->l = t->r;
false); AVL *AVL_tree::insert(AVL *r, int
t->r = parent; v) {
cout << indent;
cout<<"\n ==> Left-Left if (r == NULL) {
if (last) {cout << " [__ Rotation (LL) <==";
";indent += " ";} r = new AVL;
return t;
else {cout << " ÚÄÄ r->d = v;
";indent += " | ";} }
r->l = NULL;
cout << root- AVL *AVL_tree::LR_Rotation (AVL
>d<<"=>|"<<endl; *parent) { r->r = NULL;

printTree(root->l, AVL *t; return r;


indent, true); }
t = parent->l; } else if (v< r->d) {
};

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

r->l = insert(r->l, v); cout << t->d << " "; cout << " Inorder
Traversal:" << endl<<"\t\t\t[ ";
r = balance(r); }
AVL.inorder(r);
} else if (v >= r->d) { int main() {
cout <<" ]";
r->r = insert(r->r, v); int c, i;
//AVL.printTree(r, "", true);
r = balance(r); AVL_tree AVL;
break;
} return r; while (1) {cout<<endl;for(int
i=0;i<119;i++) case 4:
} {cout<<"Ä";}cout<<endl;
cout << "Preorder
void AVL_tree::show(AVL *p, int l) cout << " 1.Insert Element Traversal:" << endl<<"\t\t\t[ ";
{ into the tree" << endl;
AVL.preorder(r);
int i; cout << " 2.show Balanced
AVL Tree" << endl; cout <<" ]";
if (p != NULL) {
cout << " 3.InOrder traversal" // AVL.printTree(r, "", true);
show(p->r, l+ 1); << endl;
break;
cout<<" "; cout << " 4.PreOrder
traversal" << endl; case 5:
if (p == r)
cout << " 5.PostOrder cout << "Postorder
cout << " Root -> "; Traversal:" << endl<<"\t\t\t[ ";
traversal" << endl;
for (i = 0; i < l&& p != r; i++) AVL.postorder(r);
cout << " 6.Exit" << endl;
cout << " "; cout<<" ]";
cout << " \n \t\t\t\t\tEnter your
cout << p->d; Choice: ";
// AVL.printTree(r, "", true);
show(p->l, l + 1); cin >> c;
break;
} switch (c) {
case 6:
} case 1:
exit(1);
void AVL_tree::inorder(AVL *t) { cout << "\t\t\t\t\tEnter
break;
value to be inserted: ";
if (t == NULL) default:
cin >> i;
return; cout << " \a Wrong
r = AVL.insert(r, i);
Choice ,, try again" << endl;
inorder(t->l);
break;
}
cout << t->d << " ";
case 2:
}
inorder(t->r);
if (r == NULL) {
return 0;
}
cout << "\t\t\t\t\t\tTree is
}
void AVL_tree::preorder(AVL *t) { Empty" << endl;

if (t == NULL) continue;

return; }

cout << t->d << " "; cout << " Balanced AVL
Tree:" << endl<<"\t\t\t[ ";
preorder(t->l);
AVL.show(r, 1);
preorder(t->r);
cout<<"
} ]"<<endl<<endl<<endl;

void AVL_tree::postorder(AVL *t) { AVL.printTree(r, "


", true);
if (t == NULL)
cout<<endl;
return;
break;
postorder(t ->l);
case 3:
postorder(t ->r);

Eng. BASHAR A. Q. GHALEB


Data Structures II AVL Trees

😍 🤗 🌝

Eng. BASHAR A. Q. GHALEB

You might also like