An AVL tree (Adelson-Velsky and Landis, 1962) was the first self-balancing binary search tree. It keeps one extra promise on top of the BST invariant: at every node, the heights of the left and right subtrees differ by at most one. Whenever an insert or delete breaks that promise, one or two constant-time rotations repair it, so the height never exceeds about 1.44 log₂ n and every operation is guaranteed O(log n).
Think of it like
A tightrope walker
A tightrope walker never lets themselves lean far. The moment they tilt a little too much to one side, they make a small, local correction with their arms and carry on. An AVL tree does the same: each insert or delete is a small wobble, and a rotation at the lowest point that tilts too far straightens it before the lean can grow.
The balance factor
Every node stores its height. Its balance factor is the height of its left subtree minus the height of its right subtree. The AVL invariant says this number is -1, 0 or +1 everywhere. Positive means left-heavy, negative means right-heavy.
Because each node caches its height, the balance factor is O(1) to compute: height(v) = 1 + max(height(left), height(right)). After any structural change, only the nodes on the path back to the root can have new heights, so updating them costs O(log n).
Rotations: the only repair tool
A rotation moves a child up and its parent down while keeping the in-order sequence, and therefore the BST property, unchanged. It rewires three pointers and updates two heights: O(1) work.
y x
/ \ rotate right / \
x C -----------> A y
/ \ / \
A B B C
in-order before: A x B y C
in-order after: A x B y C (unchanged)- 1
Lift the child
Let
x = y.left. It will become the new root of this subtree. - 2
Move the middle subtree
Set
y.left = x.right. SubtreeBholds keys betweenxandy, so it is valid asy's new left child. - 3
Demote the old root
Set
x.right = y. - 4
Fix heights bottom-up
Recompute
yfirst (it is now lower), thenx. Returnxso the caller can relink it to the parent.
The four imbalance cases
After an update, walk back up toward the root. Let z be the lowest node whose balance factor has become +2 or -2. Let y be its child on the taller side. The direction of the step from z to y, and the lean of y, select one of four cases.
| Case | Where the extra height is | Detect | Fix |
|---|---|---|---|
| LL | Left subtree of the left child | bf(z) = +2, bf(y) >= 0 | Single right rotation at z |
| RR | Right subtree of the right child | bf(z) = -2, bf(y) <= 0 | Single left rotation at z |
| LR | Right subtree of the left child | bf(z) = +2, bf(y) < 0 | Left-rotate y, then right-rotate z |
| RL | Left subtree of the right child | bf(z) = -2, bf(y) > 0 | Right-rotate y, then left-rotate z |
bf(y) = 0 situation only arises after a deletion; it is handled as a single rotation.LL and RR: a straight line, one rotation
30 (+2) 10 (-2)
/ \
20 (+1) right-rotate 30 20 (-1) left-rotate 10
/ --------------> \ -------------->
10 20 30 20
/ \ / \
10 30 10 30LR and RL: a zigzag, two rotations
30 (+2) 30 20
/ / / \
10 (-1) ---> 20 ---> 10 30
\ /
20 10
left-rotate 10 right-rotate 30A single right rotation at 30 would not help here: it would just produce the mirror-image zigzag. The first rotation straightens the zigzag into a line (turning LR into LL), and the second rotation fixes the line. RL is the mirror image: insert 10, 30, 20, then right-rotate 30 and left-rotate 10.
Insertion, step by step
- 1
Insert like a BST
Walk down and attach the new key as a leaf.
- 2
Unwind toward the root
On the way back up (the recursion returning), recompute each node's height and balance factor.
- 3
Rebalance the first violation
At the lowest node with
|bf| = 2, apply the matching case. - 4
Stop worrying
After an insertion, that single or double rotation returns the subtree to the height it had before the insert, so no ancestor can be unbalanced. At most one rebalancing happens per insert.
| Insert | First unbalanced node | Case | Tree afterward |
|---|---|---|---|
| 10, 20 | none | 10 (-, 20) | |
| 30 | 10 (bf -2), child 20 (bf -1) | RR | 20 (10, 30) |
| 40 | none | 20 (10, 30 (-, 40)) | |
| 50 | 30 (bf -2), child 40 (bf -1) | RR | 20 (10, 40 (30, 50)) |
| 25 | 20 (bf -2), child 40 (bf +1) | RL | 30 (20 (10, 25), 40 (-, 50)) |
Deletion
Delete exactly as in a Binary Search Trees (leaf, one child, or copy the in-order successor), then walk up from the removed position updating heights and rebalancing. Two details differ from insertion.
Insertion
- The taller child always leans the same way as
zor the opposite way, never 0 - One single or double rotation restores the original height
- At most one rebalancing per insert
Deletion
- The taller child may have
bf = 0: use a single rotation - A rotation can make the subtree one level shorter
- Imbalance can propagate: up to O(log n) rotations on the way to the root
Why the height is O(log n)
Ask the opposite question: what is the fewest nodes an AVL tree of height h can have? The sparsest such tree has one subtree of height h - 1 and the other of height h - 2 (any less and it would be unbalanced), each themselves as sparse as possible.
Since the minimum node count grows exponentially in the height, the height grows only logarithmically in the node count. Solving for h gives Knuth's bound:
Perfect tree, n = 10⁶
20 levels
⌈log₂(n + 1)⌉
AVL worst case
28 levels
≈ 1.44 log₂ n
Red-black worst case
39 levels
≤ 2 log₂(n + 1)
Plain BST worst case
10⁶ levels
sorted input
AVL vs red-black trees
| Aspect | AVL tree | Red-black tree |
|---|---|---|
| Balance rule | Subtree heights differ by at most 1 | No red node has a red child; equal black height on all paths |
| Worst-case height | ≈ 1.44 log₂ n | ≈ 2 log₂ n |
| Lookups | Slightly faster (shallower tree) | Slightly slower |
| Rotations per insert | At most 2 | At most 2 |
| Rotations per delete | Up to O(log n) | At most 3 |
| Extra data per node | A height (or a 2-bit balance factor) | One color bit |
| Typical home | Read-heavy in-memory indexes and lookup tables | General-purpose libraries: TreeMap, std::map, the Linux kernel |
Complexity
| Operation | Time | Rotations | Notes |
|---|---|---|---|
| Search | O(log n) | 0 | Height < 1.44 log₂ n guaranteed |
| Insert | O(log n) | ≤ 2 | One single or double rotation at most |
| Delete | O(log n) | O(log n) | Rebalancing may cascade to the root |
| Rotation | O(1) | 1 | Three pointer changes, two height updates |
| Min, max, floor, ceiling, successor | O(log n) | 0 | Same walks as any BST |
| Space | O(n) | One height (or balance factor) per node |
All bounds are worst case, not average: that guarantee is the whole point of balancing.
Implementation
Recursive insert and delete that call `rebalance` on every node along the path back to the root. `rebalance` updates the height and applies the LL, RR, LR or RL fix when the balance factor reaches ±2.
from typing import Optional
class Node:
def __init__(self, key: int):
self.key = key
self.left: Optional["Node"] = None
self.right: Optional["Node"] = None
self.height = 1 # counted in nodes: empty = 0, leaf = 1
def h(n: Optional[Node]) -> int:
return n.height if n else 0
def update(n: Node) -> None:
n.height = 1 + max(h(n.left), h(n.right))
def balance(n: Node) -> int:
return h(n.left) - h(n.right) # > 0 means left-heavy
def rotate_right(y: Node) -> Node:
x = y.left
y.left = x.right # subtree B crosses over
x.right = y
update(y) # y is now lower: update it first
update(x)
return x
def rotate_left(x: Node) -> Node:
y = x.right
x.right = y.left
y.left = x
update(x)
update(y)
return y
def rebalance(n: Node) -> Node:
update(n)
bf = balance(n)
if bf > 1: # left-heavy
if balance(n.left) < 0: # LR: straighten the zigzag first
n.left = rotate_left(n.left)
return rotate_right(n) # LL
if bf < -1: # right-heavy
if balance(n.right) > 0: # RL
n.right = rotate_right(n.right)
return rotate_left(n) # RR
return n
def insert(node: Optional[Node], key: int) -> Node:
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
else:
return node # no duplicates
return rebalance(node)
def delete(node: Optional[Node], key: int) -> Optional[Node]:
if node is None:
return None
if key < node.key:
node.left = delete(node.left, key)
elif key > node.key:
node.right = delete(node.right, key)
else:
if node.left is None or node.right is None:
return node.left or node.right # zero or one child
succ = node.right
while succ.left:
succ = succ.left
node.key = succ.key # copy the successor, delete it below
node.right = delete(node.right, succ.key)
return rebalance(node)
def search(node: Optional[Node], key: int) -> bool:
while node:
if key == node.key:
return True
node = node.left if key < node.key else node.right
return False
root = None
for k in [10, 20, 30, 40, 50, 25]:
root = insert(root, k)
print(root.key, root.left.key, root.right.key) # 30 20 40Key takeaways
- The AVL invariant: at every node, subtree heights differ by at most one. Cached heights make the balance factor an O(1) check.
- A rotation is an O(1) local restructuring that preserves in-order order; it is the only tool AVL trees need.
- Four cases at the lowest unbalanced node: LL and RR (a straight line) need one rotation; LR and RL (a zigzag) need two.
- An insertion needs at most one single or double rotation; a deletion may need O(log n) as the imbalance propagates upward.
- The minimum node count follows a Fibonacci recurrence, so the height stays below about 1.44 log₂ n: the strictest common balanced BST.
Common pitfalls
- Updating heights in the wrong order after a rotation: the node that moved down must be updated before the node that moved up.
- Only updating heights at rotation sites; every node on the path back to the root needs its height refreshed.
- Treating a child with balance factor 0 as a zigzag during deletion. It needs a single rotation; a double rotation leaves the tree unbalanced.
- Assuming deletion stops after one fix like insertion does, and returning early before checking ancestors.
- Recomputing heights recursively instead of storing them, which makes every operation O(n).
Interview tips
- Draw the three-node line and zigzag pictures and narrate which rotation fixes each; it is faster and clearer than code.
- Justify rotations with the ordering
A < x < B < y < Cto show they never break the BST property. - Know the Fibonacci argument for the height bound; it is a favorite follow-up when you claim O(log n).
- In coding rounds, use the language's ordered map (
TreeMap,std::map,SortedList) rather than writing an AVL tree, and say so explicitly.
Real-world applications
- Read-heavy in-memory indexes and lookup tables where the shallower tree pays off.
- The Windows kernel's generic table routines include an AVL-backed variant (
RtlInsertElementGenericTableAvl). - Order-statistic and interval trees built by augmenting balanced BST nodes with extra fields.
- A clean introduction to rotations, which red-black trees, splay trees and treaps all reuse.
Practice problems
Test yourself
A node has balance factor +2 and its left child has balance factor -1. How do you fix it?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.