Skip to content

Why balanced trees stay O(log n)

Deep diveConcept

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.

Inserting 1 to 7 in order, no balancing
Step 1 of 8
plain binary search treeEmpty
  • just inserted

Insert the keys 1 to 7 in sorted order into an ordinary binary search tree. It starts empty.

0 height

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.

Degenerate tree, 1,000,000 keys1,000,000 levelsA search for the last key visits every node. Recursive code on it also runs out of stack.
Balanced tree, 1,000,000 keysabout 20 levels2²⁰ 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.

Inserting 1 to 7 into an AVL tree
Step 1 of 12
AVL treeEmpty
  • 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.

0 height
Python
def rotate_left(x):
y = x.right # y moves up
x.right = y.left # keys between x and y move across to x
y.left = x # x moves down, left of y
x.height = 1 + max(height(x.left), height(x.right))
y.height = 1 + max(height(y.left), height(y.right))
return y # the caller links y where x used to be

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.

AVL and red-black trees side by side
PropertyAVLRed-black
RuleChild heights differ by at most 1 at every nodeNo red node has a red child; every root-to-leaf path has the same number of black nodes
Worst heightabout 1.44 · log₂ nat most 2 · log₂(n + 1)
RepairsRotations, possibly at several levels after a deleteRecolouring plus at most 2 rotations per insert, 3 per delete
Best forMany lookups, fewer changesFrequent inserts and deletes
Where you meet itSome in-memory indexes and librariesJava `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.

A B-tree splitting as 10 to 70 arrive
Step 1 of 12
B-tree · at most 2 keys per nodeEmpty
  • 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.

0 levels
Binary tree, 1,000,000 keysabout 20 levelsFine in memory, where following a pointer is cheap. On disk each level can be a separate read.
B-tree, ~300 keys a node3 levels300³ 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).

07 Check yourself

Question

What does a single rotation change?

Question

Where does a B-tree get taller?

Question

A red-black tree holds 1,000,000 keys. What is the most comparisons a lookup can take?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?