AVL treee
AVL treee
AVL treee
An AVL search tree is a type of binary search tree (BST) that is self-balancing, ensuring that
the height of the tree remains logarithmic relative to the number of nodes. This balance is
achieved by maintaining the balance factor of each node, which measures the difference in
height between its left and right subtrees.
1. Balance Factor:
o For each node in the tree:
Balance Factor=Height of Left Subtree−Height of Right Subtree\text{Balance
Factor} = \text{Height of Left Subtree} - \text{Height of Right
Subtree}Balance Factor=Height of Left Subtree−Height of Right Subtree
o The balance factor must be either −1-1−1, 000, or +1+1+1. If this condition is
violated, the tree is rebalanced.
2. Balancing Operations:
o If an operation (like insertion or deletion) causes an imbalance, rotations are
performed to restore balance:
Single Rotations: Left Rotation (LL) or Right Rotation (RR).
Double Rotations: Left-Right Rotation (LR) or Right-Left Rotation (RL).
3. Height-Balanced:
o Ensures that no two subtrees differ in height by more than 1, making operations
like search, insertion, and deletion run in O(logn)O(\log n)O(logn) time.
4. Binary Search Tree Property:
o The left child of a node contains values smaller than the node, and the right child
contains values greater than the node.
Efficient Searching: Ensures logarithmic time complexity for searching due to the
balanced nature of the tree.
Consistent Performance: Balancing prevents the tree from degenerating into a linear
structure (like a linked list).
Overhead: Additional balancing operations may slightly increase the cost of insertion
and deletion.
Complexity: Implementation is more complicated compared to simple binary search
trees.
Example
3
/
2
/
1
After inserting 1, the tree becomes imbalanced because the left subtree is taller. A Right
Rotation is performed on node 3 to restore balance:
Example :
Write a c++ code to implementation of an AVL tree in C++ to insert the numbers 3, 5, 11, 8, 4, 1,
12, 7, 2, 6.
#include <iostream>
struct Node {
int data;
Node* left;
Node* right;
int height;
Node(int val) : data(val), left(nullptr), right(nullptr), height(1) {}
};
if (node) {
// Right Rotation
Node* rotateRight(Node* y) {
Node* x = y->left;
Node* T2 = x->right;
x->right = y;
y->left = T2;
updateHeight(y);
updateHeight(x);
return x;
// Left Rotation
Node* rotateLeft(Node* x) {
Node* y = x->right;
Node* T2 = y->left;
y->left = x;
x->right = T2;
updateHeight(x);
updateHeight(y);
return y;
// Left heavy
if (balanceFactor > 1) {
if (getBalanceFactor(node->left) < 0) {
// Right heavy
if (getBalanceFactor(node->right) > 0) {
// Insert function
} else {
updateHeight(root);
return balance(root);
// In-order Traversal
if (root) {
inOrder(root->left);
inOrder(root->right);
int main() {
inOrder(root);
return 0;
Question no 3: Write a program to Search the minimum subtree in the AVL tree.