AVL Trees
AVL Trees
A Binary Search Tree (BST) is a simple and efficient way to organize data, but it has a flaw—it
can become unbalanced. An unbalanced BST can degrade performance, leading to slow
searches. To solve this problem, we use AVL Trees, named after their inventors, G. M. Adelson-
Velskii and E. M. Landis.
An AVL Tree ensures balance by maintaining the height difference between left and right
subtrees of any node to no more than 1. This makes search operations much faster compared to
an unbalanced BST.
1. Unbalanced Tree: The structure becomes like a linked list. Searching can take many
steps, especially for deeper nodes.
Example: Searching for a node in an unbalanced tree with 1000 elements might take up
to 1000 steps.
2. Balanced AVL Tree: Searches are efficient. In a balanced AVL tree with 1000 elements,
the maximum search steps would be about 10.
Illustration: Refer to Figure 1, where an unbalanced and balanced tree are compared.
The balanced tree requires fewer steps for search operations.
• Either empty, or
• Has two subtrees (left and right) where the height difference ∣HL−HR∣ is at most 1 or
<=1.
Here:
• HL = Height of the left subtree
• HR= Height of the right subtree
These balance factors help detects imbalances. See Figure 2 for examples of balance factors.
When a tree becomes unbalanced after inserting or deleting a node, we use rotations to restore
balance. Four scenarios can occur: