← chapter

AVL trees

A binary search tree that rebalances itself. Height stays O(log n) — for any input.

Balance factor + rotation

Watch sorted input stay balanced

Insert 1..7 sorted — the case that killed the plain BST. AVL rotates → height 3, not 7.

Balance guarantees O(log n)

At 100000 sorted inserts: AVL height 17 vs plain BST 100000. 104× faster at n=8000.

AVL vs red-black

Takeaway

A small O(1) repair, applied consistently, converts a catastrophic worst case into an ironclad guarantee. Next: red-black trees.