Why balanced trees stay O(log n)
A binary search tree promises O(log n) lookups, but only while it stays short and bushy. Feed it sorted keys and it turns into a list. Balanced trees keep the promise by putting a limit on height and repairing it after every change, either with rotations or, in databases, with wide nodes that split.
01 Sorted inserts turn a tree into a list
A lookup in a binary search tree walks one path from the root down, so it costs the height of the tree, not the number of keys. Nothing in a plain BST controls that height. It depends entirely on the order the keys arrive in, and sorted order is the worst one, and a common one: IDs, timestamps, names read from a sorted file.
- just inserted
Insert the keys 1 to 7 in sorted order into an ordinary binary search tree. It starts empty.
02 Height is the whole cost
Each level of a full binary tree holds twice as many nodes as the one above, so n keys fit in about log₂ n levels. A tree that is allowed to lean can need n levels. The gap is enormous long before n is large.
2²⁰ is just over a million, so about 20 comparisons reach any key.A balanced tree is one with a rule that keeps the height within a constant factor of log₂ n, plus a repair step that restores the rule after each insert or delete. The rest of this page is about those two parts.
03 A rotation fixes a lean in O(1)
A rotation lifts a child above its parent while keeping the keys in order. It changes three pointers and nothing else, so it costs O(1). An AVL tree checks heights on the way back up from each insert and rotates where a node leans by 2.
- just inserted
- rule broken here
- rotated into place
The same keys, 1 to 7, into an AVL tree. Its rule: at every node, the heights of the left and right subtrees differ by at most 1.
The trace only needed single left rotations because every key arrived on the right. When a node leans right but its right child leans left (insert 1, 3, 2), one rotation is not enough: you rotate the child right first, then the node left. That pair is a double rotation, and it is still O(1).
04 Two common height rules
AVL trees and red-black trees are the two classic balanced binary trees. They differ in how strict their rule is, which trades lookup speed against repair work.
| Property | AVL | Red-black |
|---|---|---|
| Rule | Child heights differ by at most 1 at every node | No red node has a red child; every root-to-leaf path has the same number of black nodes |
| Worst height | about 1.44 · log₂ n | at most 2 · log₂(n + 1) |
| Repairs | Rotations, possibly at several levels after a delete | Recolouring plus at most 2 rotations per insert, 3 per delete |
| Best for | Many lookups, fewer changes | Frequent inserts and deletes |
| Where you meet it | Some in-memory indexes and libraries | Java `TreeMap`, typical C++ `std::map`, the Linux kernel’s `rbtree` |
Where do the height bounds come from? For AVL, ask how few nodes a tree of height h can have. The thinnest one has a subtree of height h − 1 on one side and h − 2 on the other, so the minimum count grows like the Fibonacci numbers, roughly 1.618ʰ. Turning that round gives h ≤ 1.44 · log₂ n. For red-black trees, red nodes can never be stacked, so the longest path is at most twice the shortest, and the shortest is at most log₂(n + 1).
05 Disks want wide nodes: B-trees
A binary tree on disk would cost one page read per level: about 20 reads for a million keys. Databases instead use B-trees, where one node fills a whole page (8 kB in Postgres) and holds many keys. The keys inside a node split the key space into many ranges, so each node has many children.
B-trees do not rotate. When a node overfills, it splits in two and pushes its middle key up into the parent. Only a split of the root adds a level, and it adds it at the top, so every leaf is always at the same depth.
- key just added
- too many keys
- made by a split
A small B-tree that allows at most 2 keys in a node. Insert 10 to 70 in order. It starts empty.
300³ is 27 million, so three reads find any of a million keys, and the root and upper level are almost always cached.This is the structure behind a Postgres index, and How an index makes a Postgres query fast walks through a lookup in one. The figure of about 300 keys per node is a typical order of magnitude for small keys such as integers; it depends on the key size.
06 When balance does not save you
for key in sorted(keys): bst.insert(key)Hand-written BSTs in productionA textbook BST has no balancing. Sorted or nearly sorted input makes it a list and recursion on it overflows the stack. Use your language’s balanced map instead.import bisectPython has no built-in balanced treedict is a hash table and keeps no sort order by key. For an ordered collection, bisect on a sorted list gives O(log n) search but O(n) inserts; the third-party sortedcontainers package is the usual choice.PRIMARY KEY DEFAULT gen_random_uuid()Random keys in a B-tree indexEach insert lands in a random leaf, so leaves split all over the index and pages are typically left partly empty. Sequential keys only fill the rightmost leaf. The tree stays balanced either way; the cost is extra page splits and writes.if is_balanced(node.left) and ...: height(node)Recomputing heights on every checkCalling height() from every node makes a balance check O(n²) in the worst case. Return the height and the verdict together in one bottom-up pass, which is O(n).