Don't memorize AVL rotations — watch the tree rebalance itself. An AVL tree is a binary search tree that refuses to get lopsided. After every insert it walks back up checking each node's balance factor, and the instant one tips to ±2 it rotates to fix it. Straight-line imbalances take a single rotation; zigzags take a double. That keeps the height O(log n) forever — so search never decays into a linked-list crawl.
balance factor = h(left) − h(right) · rotate at ±2 · single or double · height O(log n)
BALANCED BST
A binary search tree kept short on purpose, so height is always O(log n).
BALANCE FACTOR
bf = height(left) − height(right). AVL keeps it in {−1, 0, +1}.
ROTATION
A local O(1) re-link that rebalances while preserving the sorted order.
FOUR CASES
LL and RR need one rotation; LR and RL are zigzags that need two.
avl.sim — insert 10, 20, 30, 5, 7
Ready
Each node shows its balance factor. Insert like a normal BST; when a node reaches ±2 (red), the tree rotates to fix it. Press Step to watch a single rotation, then a double.
A binary search tree is only fast when it is bushy. Feed it sorted keys — 10, 20, 30, 40 — and it degenerates into a single leaning chain, a glorified linked list where search is O(n). The AVL tree, named after Adelson-Velsky and Landis, fixes this by enforcing one invariant: at every node, the left and right subtrees may differ in height by at most one. It tracks that difference as a balance factor. Insert as usual, then retrace the path to the root updating heights; the first node whose balance factor hits ±2 is the pivot of a rotation. A rotation just re-points three or four links — an O(1) operation — and crucially it preserves the in-order sequence, so the tree stays a valid BST. One rotation cures a straight-line lean; a zigzag needs the child straightened first, hence two.
01
Insert like a BST
Place the key by the usual less-than / greater-than comparisons, then walk back up updating heights.
02
Find the tipping point
The first node with |bf| = 2 on the way up is unbalanced and must be rotated.
03
Pick the case
Same-side lean (LL / RR) → single rotation. Zigzag (LR / RL) → rotate the child, then the node.
04
Stay sorted, stay short
Rotations are O(1) and keep the in-order order, so the tree remains a BST of height O(log n).
Search / insert / delete
O(log n)
Space
O(n)
Invariant
|bf| ≤ 1
Height
≤ 1.44 log n
The pay-off is a guarantee: no matter the insert order, an AVL tree is never more than about 1.44·log n tall, so lookups can never decay. Its close cousin the red-black tree allows a bit more slack and so rotates less on each update — a better fit for write-heavy workloads, and the balancing scheme behind many standard-library maps. AVL, being more tightly balanced, wins on read-heavy ones. Both descend from the humble binary search tree; the rotation is simply the price of keeping it honest.
Check yourself
1 · What is a node's balance factor?
AVL keeps every balance factor in {−1, 0, +1}. When an insert pushes it to ±2, that node is rebalanced with a rotation.
2 · A node reaches bf = −2 and the new key went into the right child's right subtree. Which fix?
Right-right is a straight line, so one left rotation at the unbalanced node restores balance. Zigzags (LR/RL) are the ones needing a double.
3 · Why are rotations safe to apply?
A rotation only re-points a few links and leaves the left-to-right ordering intact, so the tree stays a valid BST — just shorter.
The picture: straight lean versus zigzag
Both cases come from the page’s sequence 10, 20, 30, 5, 7. Red marks the first node on the way back up whose balance factor reaches ±2. A straight lean (10 → 20 → 30) is cured by one rotation at that node. A zigzag (10 → 5 → 7) first needs the middle node rotated so the lean becomes straight, then a second rotation at the red node. In both pictures the in-order sequence is unchanged.
Worked example, step by step
Insert 10, 20, 30, 5, 7, 3, 40, 35 into an empty AVL tree. After each plain BST insert, walk back up and compute the balance factor bf = height(left) − height(right) of every ancestor. The table shows the first ancestor that reaches ±2, the rotation it triggers, and the tree afterwards in the form root(left,right); · means an empty child.
Insert
Pivot node
bf
Fix
Rotations
Root
Height
Tree after
10
none
within ±1
no rotation
0
10
1
10
20
none
within ±1
no rotation
0
10
2
10(·,20)
30
10
−2
RR: rotate left at 10
1
20
2
20(10,30)
5
none
within ±1
no rotation
0
20
3
20(10(5,·),30)
7
10
+2
LR: rotate left at the left child, then right at 10
2
20
3
20(7(5,10),30)
3
20
+2
LL: rotate right at 20
1
7
3
7(5(3,·),20(10,30))
40
none
within ±1
no rotation
0
7
4
7(5(3,·),20(10,30(·,40)))
35
30
−2
RL: rotate right at the right child, then left at 30
2
7
4
7(5(3,·),20(10,35(30,40)))
The eight inserts produce all four cases: RR at 30, LR at 7, LL at 3 and RL at 35. Four of the eight inserts needed no rotation at all, and none needed more than one rebalancing, which is either one rotation or one double rotation. Notice that the pivot is not always the root. When 35 arrives, the tree is fine at the root and fine at 20, and only node 30 tips over, so only that small subtree is rebuilt. Also notice the height: eight keys sit in a tree of height 4, where a plain BST fed 10, 20, 30, 40 in order would already be a chain.
Complexity and trade-offs
Case
Time
Space
Why
AVL tree, search / insert
O(log n)
O(n)
Height stays within about 1.44·log₂ n. Inserting 1…1023 in sorted order gave height 10; the same keys in a plain BST give height 1023.
AVL tree, delete
O(log n)
O(n)
Finding the key is O(log n), then rotations may be needed at several levels on the way up. In 20 random 1,000-key trees the worst single delete rotated 6 times.
Plain BST, sorted input
O(n) per operation
O(n)
No balancing, so sorted keys form a chain. 127 sorted keys give height 127 instead of 7.
Plain BST, random input
O(log n) expected
O(n)
Fine on average, no guarantee. For 1,000 random keys the plain BST reached height 23; the AVL tree held 12.
Sorted array + binary search
O(log n) search, O(n) insert
O(n)
Fastest to read and smallest in memory, but every insert shifts elements.
The price of the guarantee is one extra field per node (a height or a two-bit balance) and some rotation work on writes. Inserting sorted keys 1…1023 performed 1013 rotations, almost one per key, yet each is O(1). In 5,000 random inserts no single insert needed more than one rebalancing, so insert-heavy code pays little; deletions can cascade upward, which is why write-heavy workloads often prefer a looser balance rule such as red-black trees. Read-heavy workloads gain from AVL’s tighter height.
Common mistakes
Not updating heights after a rotation
A rotation changes which node is on top, so the demoted node’s height must be recomputed before the new top’s height. Updating in the wrong order, or not at all, leaves stale heights, and the next insert computes wrong balance factors and rotates when it should not (or fails to).
Choosing the case from the new key only
Deciding LL versus LR by comparing the new key with the pivot is fragile after deletions. Look at the balance factor of the heavy child instead: for bf(n) > 1, if bf(n.left) < 0 it is a zigzag and needs the double rotation. With keys 10, 5, 7, a single right rotation at 10 leaves 5 on top with 10 below it and 7 below that, so bf(5) is −2 and the tree is still out of balance.
Rebalancing only at the parent of the new node
The first unbalanced node can be several levels up. In the example, inserting 3 under 5 breaks nothing at 5 or 7; the pivot is 20, three levels above the new node. Retrace the whole path to the root (a recursive insert does this for free).
Forgetting that deletion can need many rotations
Insert needs at most one rebalancing, so code copied from insert and run once after a delete looks right on small tests. A delete can shrink a subtree and unbalance an ancestor that is itself above another unbalanced node, so the check has to continue to the root. The worst delete in the experiment above rotated 6 times.
Rotating at bf = ±1
The invariant allows −1, 0 and +1. Rotating on |bf| ≥ 1 produces needless work and, for two keys like 10, 20, tries to rotate a tree that is already fine.
Where this shows up
Ordered in-memory maps
Any ordered map or set needs sorted iteration, range queries and a worst-case bound on lookups. A balanced BST gives all three. AVL’s tighter height suits indexes that are built once and read many times.
Interview questions
“Is this tree height-balanced?”, “convert a sorted array to a balanced BST” and “implement a self-balancing insert” all rest on the same balance-factor idea. The first is a single recursive height check.
Ranking and order statistics
Add a subtree-size field to each node and the same tree answers “what is the k-th smallest?” and “how many keys are below x?” in O(log n). Rotations just recompute the size beside the height.
Teaching other balanced trees
Red-black trees, treaps and splay trees all keep a BST short, with different bookkeeping. Rotations are the shared primitive, so learning AVL first makes the others a change of rule rather than a new mechanism.
SOLVE IT YOURSELF
Solve it: keep the tree balanced
Insert 1…7 into a plain BST and you get a linked list of height 7. An AVL tree rotates as it goes and gets height 3 — every time. Write the balancing insert yourself, in Python or TypeScript, running for real in your browser.
YOUR TASK
Implement insert(node, val) so the tree stays AVL-balanced, and avl_height(values) which inserts each value in order and returns the final height. The rotation helpers are provided — your job is deciding when to call them.
HINTS — 6 IDEAS
Insert like a normal BST first, then fix the tree on the way back up the recursion.
After recursing, refresh this node’s height, then compute its balance factor = height(left) − height(right).
A factor of +2 means left-heavy, −2 right-heavy. Anything in −1…+1 is fine — do nothing.
There are exactly four cases. LL (left-heavy, inserted left of the left child) → rotate right. RR → rotate left.
LR (left-heavy but inserted right of the left child) needs two rotations: rotate the child left first, which turns it into LL, then rotate right. RL is the mirror.
Duplicates: return the node unchanged rather than inserting twice, or the height bookkeeping drifts.
CPython · WebAssembly✓ Solved
1
1
Questions
AVL tree vs red-black tree?
Both are self-balancing BSTs with O(log n) operations. AVL is more strictly balanced, so lookups are slightly faster — good for read-heavy use. Red-black trees tolerate a little more imbalance and do fewer rotations per update, which suits write-heavy use and is why they back many standard-library maps and sets.
Why not just use a plain BST?
A plain BST has no balance guarantee. Insert already-sorted data and it becomes a single chain of height n, making search O(n). AVL rotations keep the height O(log n) no matter the insertion order.
When is a double rotation needed?
When the imbalance is a zigzag: the heavy child leans one way and its heavy child leans the other (left-right or right-left). You first rotate the child to straighten the line into an LL or RR shape, then rotate the unbalanced node.
Sorted, and never lopsided.
Track a balance factor at each node, rotate the moment it hits ±2, and a binary search tree stays O(log n) tall for every insert order.