Insert the keys 1 to 1,000 in order. A plain search tree grows 1,000 levels deep. A red-black tree stays at 17, because five colour rules force a small repair whenever a path gets too long.
Pick a tree and drag Keys inserted. Watch the plain tree lean into a staircase while the red-black tree stays bushy. Then we build, piece by piece, the rules, the height proof, rotations, insertion and deletion.
You need binary search trees (search, insert, in-order walk) and a little Python. We build the rest from zero.
Based on Chapter 13 of Introduction to Algorithms by Cormen, Leiserson, Rivest and Stein (CLRS). Before: Binary Search Trees. After: B-Trees.
Both trees run this page's code: a plain BST insert, and the CLRS red-black insert with its fix-up. The shuffled order is one fixed random order. The 1,000-key figure in the title comes from the same code run offline: 17 levels. No valid red-black tree with 1,000 keys is taller.
Chapter 0
See how insertion order alone can turn a tree into a list, and what a guarantee would buy
Your app gives each new user an ID: 1, 2, 3, and so on. You store the IDs in a binary search tree so that lookups are fast. Each new ID is larger than every ID before it, so it always goes right. After 1,000 users the tree is a chain 1,000 keys long.
A search walks one path from the root down, so it costs one comparison per level. The height of a tree is the number of keys on its longest path from the root down. A chain of n keys has height n. A search in it is a scan of a list.
The shape of a plain BST depends on the order the keys arrive, not on the keys. Sorted IDs, timestamps and names in alphabetical order are common inputs. A tree that cannot protect itself from them gives no guarantee.
Each bar is the worst number of comparisons for one search. Drag n from ten keys to a billion.
Exact counts, computed: the plain BST fed sorted keys is n levels deep. The red-black bar is the tallest valid red-black tree with n keys. The perfect bar is the shortest any binary tree can be, the ceiling of lg(n + 1).
With numbers: at n = 1,000 the sorted plain tree needs up to 1,000 comparisons per search. A red-black tree needs at most 17. No binary tree can beat 10, because 10 full levels hold only 1,023 keys. At a million keys the three counts are 1,000,000, 37 and 20.
The failure: a plain BST in production. Symptom: lookups slow down in step with the data, not with its logarithm. Measure: log the tree height next to the key count. A height near n means a chain. Fix: a tree that rebalances itself on every insert and delete. A red-black tree is a BST that paints each key red or black and repairs the shape whenever a colour rule breaks.
Chapter 1
Paint each key red or black, and see which two rules keep every path within a factor of two
A red-black tree stores one extra bit per key: its colour. It also replaces every empty child pointer with a NIL leaf, a stand-in node that is always black and holds no key. In code, one shared sentinel object, T.nil, plays every NIL leaf. The fix-up code can then read the colour of any child or uncle without a null check.
| Rule | Statement | What it does |
|---|---|---|
| 1 | Every node is red or black. | one bit per key |
| 2 | The root is black. | a fixed start for counting |
| 3 | Every NIL leaf is black. | a fixed end for counting |
| 4 | A red node has two black children. | no two reds in a row on a path |
| 5 | From each node, every path down to a NIL leaf has the same number of black nodes. | the black skeleton is perfectly balanced |
Rules 4 and 5 do the work. Rule 5 says the black nodes form a perfectly balanced frame. Rule 4 says red nodes can only sit between black ones, never two in a row. Click the nodes below to break each rule.
Each square under the tree is a NIL leaf, labelled with the black keys on its path. Click a key to flip its colour. Find a flip that breaks rule 4 and one that breaks rule 5.
A hand-built tree with keys 3, 5, 7, 10, 13, 15, 20 and 25. The checker runs rules 2, 4 and 5 after every click; rules 1 and 3 hold by construction.
Now count. Pick any path from the root down to a NIL leaf. Call the number of keys on it ℓ, its length. Call the number of black keys on it b; rule 5 says b is the same for every path. Rule 2 makes the first key black, and rule 4 lets at most one red follow each black.
b is at most ell, and ell is at most two b.
Every path holds the same b black keys. An all-black path has length b. A path that slips one red after each black has length 2b. So any path length ℓ sits between b and 2b, and the longest path is at most twice the shortest.
The tree in the device has b = 2. The path 10, 5, 3 has ℓ = 3. The path 10, 20, 15, 13 has ℓ = 4 = 2b, the longest allowed. No valid colouring of a b = 2 tree can hold a path of 5.
The failure: colouring a new key black. Symptom: the tree looks fine, but a later insert loops or crashes in the fix-up. Measure: a checker that returns the black count of each subtree and fails when left and right differ. Fix: new keys are red, as Chapter 4 explains.
Chapter 2
Prove that a tree with n keys is at most 2 lg(n + 1) levels deep
Paths differ by at most a factor of two, but that alone allows a tall tree. We need one more link: a tall tree must hold many keys.
The black-height of a node x, written bh(x), counts the black nodes on a path from x down to a NIL leaf. It skips x and counts the NIL. Rule 5 makes it the same on every path. Call the number of keys in the subtree under x, x included, s(x).
s of x is at least two to the bh of x, minus one.
Take the black-height bh(x). Raise 2 to it and take away 1. The subtree under x holds at least that many keys s(x).
A root with bh = 4 sits on at least 24 − 1 = 15 keys. With bh = 3 it needs at least 7. A tree of 6 keys cannot have black-height 3.
The proof is by induction on height. A NIL leaf has bh = 0 and holds 0 keys. A black child of x has black-height bh(x) − 1, and a red child has bh(x). So each child has at least bh(x) − 1. Each child's subtree then holds at least 2bh(x)−1 − 1 keys. Add both and x itself: 2 × (2bh(x)−1 − 1) + 1 = 2bh(x) − 1.
Left: the shortest path, all black. Right: the longest path, a red after each black. Middle: the fewest keys that black-height forces. Drag the black-height.
The perfect black tree is the smallest tree with that black-height. Path lengths follow from rules 2, 4 and 5.
Now join the two facts. Let the tree hold n keys and have height h. By rule 4, at least half the nodes below the root on the longest path are black, so bh(root) ≥ h/2. So n ≥ 2h/2 − 1. Take logs.
h is at most two times log base two of n plus one.
Add 1 to the key count n. Take log base two. Double it. The height h never passes that number.
n = 1,000,000: lg(1,000,001) ≈ 19.93, so h ≤ 39.86, that is 39 levels. The tallest valid tree with a million keys, found by search, has 37. A sorted plain BST has 1,000,000.
The failure: reading the bound as the typical height. Symptom: capacity plans come out too pessimistic. Measure: 1,000 random keys give about 12 levels, against a bound of 19.9. Fix: use the bound for guarantees and the measured height for averages.
Chapter 3
Lift one key over its parent with six pointer changes, and keep the sorted order intact
Recolouring cannot fix every broken rule. Sometimes a key must move up a level. A rotation does that. It swaps a parent and child along one edge and passes one subtree across. It compares no keys and copies no data, so it costs O(1).
A left rotation at x needs a right child y. Afterwards y sits where x was, and x is y's left child. Call the three subtrees around them α (x's left), β (y's left) and γ (y's right). Only β changes parent: it moves from y to x. A right rotation at y is the mirror and undoes it.
Triangles are whole subtrees. Purple marks β, the subtree that changes parent. Rotate, and read the in-order line under the tree.
A schematic: each triangle stands for any subtree, empty or large. The pointer count is from the CLRS LEFT-ROTATE code below.
Why is this safe? An in-order walk of a BST visits keys in sorted order. Name the sorted order of the five parts.
Alpha is less than x, less than beta, less than y, less than gamma.
Walk the tree in order before the rotation: α, x, β, y, γ. Walk it after: the same five parts in the same order. The sorted order holds, so the result is still a valid BST.
With made-up keys: α = {1, 2}, x = 3, β = {4}, y = 5, γ = {6, 7}. Both shapes read 1 2 3 4 5 6 7. The depth of α grows by 1 and the depth of γ shrinks by 1; β stays at the same depth.
pythondef left_rotate(T, x): y = x.right # y must exist x.right = y.left # 1: beta moves to x if y.left is not T.nil: y.left.parent = x # 2 y.parent = x.parent # 3: y takes x's place if x.parent is T.nil: T.root = y # 4: one of these three elif x is x.parent.left: x.parent.left = y else: x.parent.right = y y.left = x # 5 x.parent = y # 6
The failure: forgetting one parent pointer. Symptom: the tree prints fine top down, but walks that climb parent links loop or skip keys. Measure: after each rotation, assert that every child's parent points back. Fix: update all six links, including the sentinel's when β is NIL.
Chapter 4
Insert like a plain BST, colour the new key red, and fix a red parent with one of three cases
Insert the new key z as in a plain BST: walk down, attach it as a leaf with two NIL children. Then choose its colour. Black would add one black key to every path through z and break rule 5 everywhere below its parent. Red changes no black count. It can only break rule 4, if z's parent is red, or rule 2, if the tree was empty.
So the only real problem is a red-red pair: z and its parent p are both red. The grandparent g must be black, because the tree was valid before. The repair reads the uncle u, p's sibling. Call z an outer child if it hangs on the same side of p as p hangs on g, and an inner child otherwise.
| Case | When | Do | Then |
|---|---|---|---|
| 1 | uncle u is red | paint p and u black, g red | set z = g and check again, two levels up |
| 2 | u is black, z is inner | rotate at p, away from z's side | z is now outer: go to case 3 |
| 3 | u is black, z is outer | paint p black, g red, rotate at g toward u | done |
Case 1 keeps black counts: each path through g loses g's black and gains p's or u's. Last, the code paints the root black. That adds one black to every path at once, so rule 5 holds.
Warm is the new key z, blue is the uncle, purple marks a rotation. Pick a key sequence, then press Step to see each repair.
Each frame comes from this page's RB-INSERT and RB-INSERT-FIXUP, written from the CLRS pseudocode. The random keys come from 1 to 60.
With numbers, keys 1 to 7 in order. Key 3 makes a red-red pair with a NIL (black) uncle and an outer z: case 3 rotates at 1. Key 4 meets a red uncle: case 1, then the code paints the root black again. Key 5 is case 3 again, key 6 is case 1, and key 7 is case 3. The total is 3 rotations, and the tree ends 4 levels deep where a plain BST is 7.
Case 1 can climb up to about h/2 times, two levels per step, with no rotation. Cases 2 and 3 end the repair. So one insertion does at most 2 rotations. On random keys this page's code measures about 0.58 rotations per insert.
pythondef insert_fixup(T, z): while z.parent.color == RED: p, g = z.parent, z.parent.parent if p is g.left: u = g.right # the uncle if u.color == RED: # case 1 p.color = u.color = BLACK; g.color = RED; z = g else: if z is p.right: # case 2: inner z = p; left_rotate(T, z) z.parent.color = BLACK # case 3: outer z.parent.parent.color = RED right_rotate(T, z.parent.parent) else: # mirror: swap left and right ... T.root.color = BLACK
The failure: a wrong mirror branch. Symptom: trees built from ascending keys pass every check, and descending keys break rule 4. Measure: run the rule checker after inserts in both orders. Fix: write the mirror by swapping every left with right, including the rotation names.
Chapter 5
Remove a key as in a plain BST, track the colour that left, and pay back a lost black with four sibling cases
Delete key z as in a plain BST. With at most one child, splice z out. With two children, its successor y (the smallest key in its right subtree) moves into z's place and takes z's colour. Either way, one node leaves its old spot, and x is the node that moves into that spot, possibly a NIL.
If the node that left was red, no black count changed and nothing is broken. If it was black, every path through x is one black short. Give x an extra black: x now counts twice, a double black. If x is red, paint it black and stop. Otherwise push the extra black around using x's sibling w.
| Case | When (x is a left child) | Do | Then |
|---|---|---|---|
| 1 | w is red | w black, parent red, rotate at parent toward x | x has a black sibling now: case 2, 3 or 4 |
| 2 | w black, both its children black | paint w red | the extra black moves up to the parent |
| 3 | w black, near child red, far child black | swap colours of w and near child, rotate at w away from x | the far child is red: case 4 |
| 4 | w black, far child red | w takes the parent's colour, parent and far child black, rotate at parent toward x | done |
Case 2 can climb the tree with no rotation, and it ends at once if the parent is red. Case 1 leads to 2, 3 or 4; case 3 leads to 4; case 4 ends. A case 1 that leads to case 2 also ends, because its parent is red. So one deletion does at most 3 rotations.
Warm is x, carrying the extra black. Blue is the sibling w. Tap a key to delete it, then Step. Try 6, then Reset and try 4; then 1 followed by 4.
The start tree is the keys 1 to 10 inserted in order. Frames come from this page's RB-DELETE and RB-DELETE-FIXUP, written from the CLRS pseudocode.
With numbers: insert 1 to 5 in order. The root is 2 (black), with 1 (black) on the left and 4 (black) on the right; 4 has red children 3 and 5. Delete 1. It is a black leaf, so x is a NIL with an extra black. The sibling 4 is black and its far child 5 is red: case 4. Key 4 takes 2's black, 2 and 5 turn black, and a left rotation at 2 lifts 4 to the root. One rotation, and every path has two blacks again.
The failure: a NIL x with a stale parent. Symptom: deleting a key whose successor is its own right child corrupts the tree. Measure: delete every key of a test tree one at a time and run the checker after each. Fix: when y's parent is z, set x.parent = y even when x is the sentinel. That is why CLRS uses one shared NIL object.
Chapter 6
Glue each black key to its red children and see a perfectly balanced tree of wide nodes
The cases look arbitrary until you see what the colours encode. A 2-3-4 tree is a search tree whose nodes hold 1, 2 or 3 keys and have one more child than keys. Every leaf sits at the same depth. It is a B-tree with at most 4 children per node.
Glue each black key to its red children. Each glued group is one 2-3-4 node. Call the number of red children of a black key r, from 0 to 2, and the number of keys in its glued node k.
k equals one plus r.
Start at a black key. Count its red children r. Add 1 for the black key itself. That is k, the size of the wide node. Rule 4 stops a red from having a red child, so k never passes 3.
Root 10 (black) has one red child 5, whose children 3 and 7 are black: r = 1, k = 2, the node [5 10]. Key 20 (black) has red children 15 and 25: r = 2, k = 3, the node [15 20 25]. Keys 3 and 7 have r = 0: one-key nodes.
Drag the key count to grow a tree, then switch views. In the 2-3-4 view, pink boxes are glued nodes; check that every leaf box sits on one line.
The keys arrive in one fixed random order from 1 to 60. The 2-3-4 view is computed from the red-black tree, not built separately.
Now the rules read plainly. Rule 5, equal black counts, is “every leaf at the same depth”. Rule 4 is “at most 3 keys per node”. Insert case 1, the red uncle, splits a full node. Key g goes up into its parent's node, and p and u stay behind as two small nodes. Cases 2 and 3 add a key to a 2-key node; the rotation puts the middle key at the black centre.
The failure: a red key with a red child. Symptom: the checker reports rule 4 broken after a hand-written fix-up. Measure: in the 2-3-4 view, a full 3-key node has taken a fourth key. Fix: the repair is the B-tree split; Chapter 4's case 1 is that split in colours.
Chapter 7
Insert and delete any keys, and watch the rules, the height and the bound after every change
Everything so far runs here at once. Type a key and insert or delete it, or feed the tree a sorted run. The checker re-tests rules 2, 4 and 5 after every change. The read-out compares the height with the bound 2 lg(n + 1).
Turn on black-heights to see rule 5 at every key, or NIL leaves to see rule 3. Try fifteen keys in order, then delete the root a few times.
Keys run from 1 to 99. The tree holds at most 40 keys so it stays readable on a phone. All counts come from this page's code.
| Try | What you should see |
|---|---|
| Insert 1 to 15 | 9 rotations; height 6 against a bound of 8; a plain BST would be 15 deep |
| Black-heights on | both children of every key show the same number |
| Delete root, three times | the successor moves up; the checker stays green |
| Insert 5 random, many times | about one rotation per two inserts |
One more number to look for: after 1 to 15 in order, only 4 of the 15 keys are red. Sorted runs push the tree toward its tallest legal shape, but most keys end black. A tree can hold far more red: a perfect 15-key tree with levels black, red, black, red is valid with 10 reds.
Chapter 8
Trade a shorter tree for more repair work, and see which systems chose which
An AVL tree (Adelson-Velsky and Landis, 1962) keeps a stricter rule: at every node the heights of the two subtrees differ by at most 1. Stricter balance means a shorter tree. Call the number of keys n and the height h, counted in keys as before.
h is less than one point four four times log base two of n plus two, minus zero point three three.
Add 2 to n. Take log base two. Multiply by 1.44 and take away 0.33. An AVL tree's height h stays below that. The red-black ceiling uses 2 where AVL uses 1.44.
n = 1,000,000: lg(1,000,002) ≈ 19.93; 1.44 × 19.93 − 0.33 ≈ 28.4, so at most 28 levels. A red-black tree can reach 37. So a worst-case search costs 28 comparisons against 37.
The price is repair work. An AVL insert does one single or double rotation at most, like red-black. An AVL delete can need a rotation at every level on the way up, O(log n) rotations. A red-black delete stops at 3. Red-black needs one bit per key; AVL stores a height or a balance factor.
Teal is AVL, ink and red are red-black. Drag the key count and the order, then delete half the keys and compare the rotations.
Both trees run this page's code: a textbook AVL insert and delete, and the CLRS red-black operations. A double rotation counts as two. Deleted keys are every other key in a fixed random order.
| Where | What it stores | Why an ordered tree |
|---|---|---|
| Java TreeMap, TreeSet | sorted maps and sets | range views like headMap need order; the docs name it a red-black tree |
| C++ std::map (libstdc++) | ordered containers | the standard asks for log-time insert, erase and find |
| Linux kernel rbtree | the scheduler's runnable tasks, epoll's watched files | fast insert, delete by key, and the leftmost (smallest) entry |
| Nginx | connection timers | the next timer to expire is the minimum |
Why not a heap for the scheduler? A heap finds the minimum fast, but removing a task that blocks needs it found first, which costs O(n) in a heap. The tree does it in O(log n). Disks and large indexes use B-trees instead: wide nodes mean fewer slow reads.
The failure: an ordered tree where no order is needed. Symptom: point lookups cost about 20 pointer hops at a million keys. Measure: check whether any code asks for ranges, the minimum or sorted iteration. Fix: if not, a hash table does point lookups in O(1) expected time.
Chapter 9
Keep the rules, the numbers and the code in one place
A red-black tree is a BST with one colour bit per key. Five rules keep every path within twice the shortest, so the height stays under 2 lg(n + 1). Insert adds a red key and repairs with at most 2 rotations. Delete repays a lost black with at most 3.
| Term or number | Meaning |
|---|---|
| black-height bh(x) | black nodes from x down to a NIL, NIL counted, x not |
| b ≤ ℓ ≤ 2b | every root-to-NIL path is between b and 2b keys long |
| s(x) ≥ 2bh(x) − 1 | a subtree with black-height 4 holds at least 15 keys |
| h ≤ 2 lg(n + 1) | 39 levels at n = 1,000,000; the tallest real tree has 37 |
| ≤ 2 rotations | per insert; case 1 may recolour up the tree |
| ≤ 3 rotations | per delete; case 2 may climb without rotating |
| about 0.58 | rotations per insert on random keys (this page's code) |
| k = 1 + r | keys in the 2-3-4 node of a black key with r red children |
| h < 1.44 lg(n + 2) − 0.33 | AVL height: 28 levels at a million keys |
pythonRED, BLACK = 0, 1 def insert(T, z): # z.key set; T.nil is the black sentinel y, x = T.nil, T.root while x is not T.nil: y = x x = x.left if z.key < x.key else x.right z.parent = y if y is T.nil: T.root = z elif z.key < y.key: y.left = z else: y.right = z z.left = z.right = T.nil z.color = RED # red keeps every black count insert_fixup(T, z) # Chapter 4 def check(T, x): # returns bh(x), raises if a rule breaks if x is T.nil: return 0 if x.color == RED: assert x.left.color == x.right.color == BLACK # rule 4 l, r = check(T, x.left), check(T, x.right) assert l == r # rule 5 return l + (x.left.color == BLACK) # bh counts the child level
CLRS Chapter 14 builds on this one. An order-statistic tree stores a subtree size in each key, to find the k-th smallest in O(log n). An interval tree stores the largest endpoint below each key. Both work because a rotation touches only two keys' extra fields.
Credit: this lesson follows Chapter 13, Red-Black Trees, of Introduction to Algorithms by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press). Red-black trees come from Rudolf Bayer's symmetric binary B-trees (1972), given their colours by Leonidas Guibas and Robert Sedgewick (1978).
Explain it back with Present or Teach, or go back to the hero and predict the red-black height before you drag the keys.