Info & Theory
An AVL tree (Adelson-Velsky & Landis, 1962) is a
binary search tree that keeps itself height-balanced after
every insertion and deletion, guaranteeing
O(log n) search, insert, and delete in the
worst case.
Balance factor
Every node stores a balance factor:
height(left) − height(right). The AVL invariant
requires this value to stay in {−1, 0, 1} for
every node. After a change, heights are recomputed bottom-up
from the modified node to the root.
Detecting imbalance
Walking upward, the first ancestor whose balance factor falls
outside {−1,0,1} is the pivot for rebalancing.
The four rotation cases
LL: left-heavy, left child left-heavy → single right rotation.RR: right-heavy, right child right-heavy → single left rotation.LR: left-heavy, left child right-heavy → rotate left child left, then rotate node right.RL: right-heavy, right child left-heavy → rotate right child right, then rotate node left.
Each rotation is an O(1) pointer rewrite; at most one (single or double) rotation is needed after an insertion, while deletion can require a rotation at every level up to the root.
Why it matters
A plain unbalanced BST degrades to O(n) on
sorted input (it becomes a linked list). AVL's strict
balance keeps height at
O(log n) ≈ 1.44·log₂(n+2), so lookups stay
fast regardless of insertion order.