AVL Tree
An AVL tree is a Binary Search Tree that enforces a strict balance rule after every modification. Named after its inventors Adelson-Velsky and Landis (1962), it was the first self-balancing BST ever invented.
The rule is simple: for every node, the heights of its left and right subtrees must differ by at most 1. This guarantee keeps the tree height at \(O(\log n)\) always — no degenerate cases possible.
The balance factor
Every node stores its balance factor:
In a valid AVL tree, every node's balance factor must be one of: -1, 0, or +1.
- -1 — right subtree is one level taller
- 0 — perfectly balanced at this node
- +1 — left subtree is one level taller
After any insert or delete, if any node's balance factor becomes ±2, the tree must be repaired using rotations.
← → arrow keys to step · click elements to interact
AVL Tree: Insert with Rotations
Rotations — the repair tool
A rotation restructures a small part of the tree to restore balance without violating the BST property. There are four rotation types, but only two fundamental ones:
Left Rotation
Used when the right subtree is too tall (balance factor = -2) due to a right-right insertion:
B becomes the new root, A becomes B's left child, and B's old left child (if any) becomes A's right child.
Right Rotation
The mirror case — used when the left subtree is too tall (balance factor = +2) due to a left-left insertion:
Double rotations
For left-right and right-left cases (the imbalance is "zigzag" shaped), you need two rotations:
- Left-Right: Left rotate the child, then right rotate the root
- Right-Left: Right rotate the child, then left rotate the root
When to use AVL vs Red-Black
AVL trees are more strictly balanced than Red-Black trees, making lookups slightly faster (shorter maximum path). However, they perform more rotations on insert and delete, making writes slightly slower. Choose AVL when read-heavy workloads dominate. Most language standard libraries (Java TreeMap, C++ std::map) use Red-Black trees for their better write performance.