Balanced trees: the red-black guarantee
◈ 3 cardsWhy balance matters, the five RB invariants at a glance, and the O(lg n) height bound — guarantee, not case analysis.
The problem balance solves
The previous lesson left us with a landmine: a plain BST built from sorted input degenerates into a height- chain, and every operation collapses to . A balanced BST fixes this by keeping the height no matter the insertion order, so all operations stay in the worst case. A red-black tree is the workhorse balanced BST: a BST with one extra color bit (red or black) per node, plus rebalancing logic on insert and delete.
For this exam you need the guarantee and why it holds — not the memorized fixup cases. So this lesson is deliberately overview-only.
The five red-black properties
- Every node is either red or black.
- The root is black.
- Every leaf (the
NILsentinel) is black. - If a node is red, both its children are black (no two reds in a row on any path).
- For every node, all simple paths down to descendant leaves contain the same number of black nodes (this count is the node's black-height).
Why these five force O(lg n) height
Look at any root-to-leaf path. Property 4 forbids consecutive red nodes, so at most half the nodes on the path can be red — meaning at least half are black. Property 5 says every such path has the same number of black nodes. So the longest possible path (alternating red/black) is at most twice the shortest (all black). That bounded ratio is the whole game.
Formally (Lemma 13.1): the subtree at a node of black-height holds at least internal nodes, and since black-height is at least , you get , i.e.
Because every BST operation is (Lesson 3.2), this single bound delivers worst-case SEARCH, MINIMUM, MAXIMUM, SUCCESSOR, PREDECESSOR, INSERT, and DELETE.
Rebalancing: rotations are O(1), and there are O(1) of them
Insert and delete restore the properties with rotations — local pointer twists (LEFT-ROTATE, RIGHT-ROTATE) that preserve the BST ordering while reshaping the tree — plus recolorings. The headline numbers: RB-INSERT does at most 2 rotations, RB-DELETE at most 3, each plus recolorings, for total. That constant rotation bound is why red-black trees power Java's TreeMap, C++'s std::map, and the Linux kernel's scheduler — modifications complete in predictable, near-constant structural work.
Worked example — the doubling argument, concretely
Take a red-black tree with black-height 3 at the root. Lemma 13.1 says it holds at least internal nodes. The shortest root-to-leaf path is 3 nodes (all black); the longest is at most 6 (black-red-black-red-black-red). For keys, the bound gives — so any operation touches at most ~60 nodes, versus a billion for a degenerate chain. That is the difference between instant and timeout, and you derived it from five color rules, not from any rotation case.