What is an AVL Tree?
A plain BST offers no guarantee about its shape: insert values in the wrong order and it degenerates into a linked list with O(n) operations (see BST Insertion). An AVL tree fixes this by adding one rule on top of the normal BST ordering: for every node, the heights of its left and right subtrees may differ by at most 1. This is called the balance factor, and it's recalculated bottom-up after every insertion or deletion.
How Do Rotations Work?
Whenever an insertion pushes a node's balance factor to +2 or -2, the tree is out of balance and needs a rotation, a local rearrangement of a few pointers that restores the height rule without breaking the BST ordering. There are four possible imbalance shapes, and each has a matching fix: a single rotation for the two "straight-line" cases (Left-Left, Right-Right), and a double rotation for the two "zig-zag" cases (Left-Right, Right-Left).
Algorithm Steps (Insertion)
- Insert the value the normal BST way (compare and recurse left/right)
- On the way back up the recursion, update each ancestor's height
- Compute the balance factor: height(left) − height(right)
- If the balance factor is +2 or -2, identify which of the 4 cases applies and rotate:
- Left-Left → single right rotation
- Right-Right → single left rotation
- Left-Right → left rotation on the left child, then right rotation on the node
- Right-Left → right rotation on the right child, then left rotation on the node
- Return the (possibly new) subtree root to the parent call
Time Complexity
- Best/Average/Worst Case: Height is always O(log n) → O(log n).
Time Complexity Analysis
Space Complexity
Because at most O(log n) ancestors need their balance factor rechecked after an insertion, and each rotation touches only a constant number of pointers, a single insertion or deletion does at most one rotation (single or double) to restore balance, so the extra bookkeeping AVL trees do is cheap.
The payoff is that an AVL tree's height is always O(log n), no matter what order values are inserted in. Unlike a plain BST, it can never degrade into a skewed shape. This makes search, insertion, and deletion all worst-case O(log n), not just average-case.