RED-BLACK TREE

Four colour rules that keep a binary search tree from turning into a list

L318 MINALGORITHMS
PREDICT

Insert 10, 20, 15 into an empty red-black tree. New nodes are red, a red node may not have a red child, and every path down must pass the same number of black nodes. 15 is red under red 20, and its uncle is a black NIL. What restores the rules?

A binary search tree is only fast if it is shallow. Insert sorted keys and every node hangs off the right of the last one: height n. A red-black tree colours each node and keeps four rules: every node is red or black (NIL leaves count as black), the root is black, a red node has no red child, and every path from a node down to a NIL leaf passes the same number of black nodes. Together they force height ≤ 2·log2(n+1).

An insert adds a red node, which can only break the no-red-red rule. The fix looks at the uncle. Red uncle: recolour and move up. Black uncle: rotate, once if the path is straight, twice if it zig-zags.

▶ SIMULATION
LAST INSERT
empty tree
MEASURED
n = 0
height 0 ≤ 2·log2(n+1) = 0
black-height 0
red-red pairs 0
RB FIXUP
rotations 0
recolourings 0
no fault
treeempty
✓ root is black✓ no red node has a red child✓ every root-to-NIL path has the same number of black nodes✓ height ≤ 2·log2(n+1)
SCHEDULE
01[BST-INSERT]insert 1
02[BST-INSERT]insert 2
03[BST-INSERT]insert 3
04[BST-INSERT]insert 4
05[BST-INSERT]insert 5
06[BST-INSERT]insert 6
07[BST-INSERT]insert 7
08[CHECK]check every invariant
Start of naive bst, keys 1..7 scenario. 8 steps.
Red-black rules
  1. every node is RED or BLACK; NIL leaves are BLACK
  2. the root is BLACK
  3. a RED node has no RED child
  4. every root-to-NIL path has the same number of BLACK nodes
  => height <= 2 * log2(n + 1)

RB-INSERT(T, z): BST insert z, colour it RED, then
while z.parent is RED:
  p = z.parent; g = p.parent; u = sibling of p
  if u is RED:                       // case 1
    p, u = BLACK; g = RED; z = g     // recolour, move up
  else:
    if z is the inner child:         // case 2: zig-zag
      z = p; rotate(p) away from z   // now a straight line
      p = z.parent
    p = BLACK; g = RED               // case 3: straight line
    rotate(g) toward the other side  // loop ends: p is BLACK
root = BLACK

At most 2 rotations per insert; recolouring may climb O(log n).

Watch the invariant strip. NAIVE BST is the same insert with the fixup removed, so its nodes still get colours and the colour rules go red at the third key. A plain BST never promised those rules; the failure that matters is the height bound, which breaks at the sixth key. RED-BLACK on the same sorted keys ends at height 4 with every rule green. EVERY INSERT CASE shows a straight-line rotation at 30, a recolouring at 15, the zig-zag double rotation at 13 and another recolouring at 5.

BREAK IT NOT YET

The fault makes the next insert skip its rotations; recolouring still runs. Inject it before an insert that needs a rotation so the tree ends up breaking a red-black rule. Inserts that only recolour survive it.

GOAL: some red-black rule is broken after an insert

FIX IT NOT YET

This fixup handles a red uncle and the straight-line case, which is enough for sorted input. The grader inserts sorted, reversed and seeded-random keys and checks every red-black rule, BST order and the height bound after each insert. Make it pass.

Mental model:

black-height is the real balance measure: every path carries the same number of black nodes, and red nodes are slack that may never appear twice in a row. An insert only creates red-red trouble. The uncle decides the fix: red means push the problem up by recolouring, black means fix it here with at most two rotations, and a zig-zag needs both.

IN PRODUCTION

Java TreeMap and TreeSet, the usual implementation of C++ std::map and std::set, the Linux kernel's rbtree (the scheduler run queue under CFS and its successor EEVDF, epoll), and timer queues and interval indexes that need ordered keys with O(log n) worst case.

IN INTERVIEWS

“Why use a balanced tree over a hash map?” (ordered iteration, range queries, worst-case bounds) and “walk me through a red-black insert.” Name the rules, say why the uncle's colour picks the case, and draw the zig-zag double rotation. Most people forget that one.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: B-TREE →