Red-Black Trees

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.

Feed one tree its keys

15

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

Sorted Keys Break a Search Tree

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.

Count the levels a search walks

Each bar is the worst number of comparisons for one search. Drag n from ten keys to a billion.

1,000

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.

The road

  1. The five rules: colours, NIL leaves, and why no path can be more than twice another.
  2. The height bound: the proof that h stays under 2 lg(n + 1).
  3. Rotations: the one move that changes shape and keeps order.
  4. Insertion: insert red, then three cases (the hero's red-black tree).
  5. Deletion: the double black and four sibling cases.
  6. The 2-3-4 view: the same tree as a B-tree with wide nodes.
  7. The playground: insert, delete and check every rule live.
  8. Red-black against AVL: height against repair cost, and who uses which.
  9. The field guide: numbers, code and links.
You insert the keys 1, 2, 3, ..., 1,000 in that order into an empty plain BST. What is its height?

Chapter 1

The Five Rules

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.

RuleStatementWhat it does
1Every node is red or black.one bit per key
2The root is black.a fixed start for counting
3Every NIL leaf is black.a fixed end for counting
4A red node has two black children.no two reds in a row on a path
5From 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.

Break the rules on purpose

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.

Say it aloud

b is at most ell, and ell is at most two b.

ℓ
ell the length of one path from the root down to a NIL leaf, counted in keys.
b
b the black keys on that path, counting the root. Rule 5 makes it the same for every path.
2b
two b the most keys a path can hold: every black key followed by one red.
≤
is at most the left side is never larger than the right.
In plain words

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.

With numbers

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.

Every path from the root of a red-black tree to a NIL leaf has 4 black keys. What is the longest a path can be?

Chapter 2

Why the Height Stays Logarithmic

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).

Say it aloud

s of x is at least two to the bh of x, minus one.

s(x)
s of x the number of keys in the subtree rooted at x, x included.
2bh(x)
two to the bh of x 2 multiplied by itself bh(x) times, where bh(x) is the black-height of x.
− 1
minus one a perfect all-black tree with k levels holds 2k − 1 keys.
In plain words

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).

With numbers

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.

Stretch a path with reds

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.

3

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.

Say it aloud

h is at most two times log base two of n plus one.

h
h the height: the number of keys on the longest path from the root down.
n
n the number of keys in the whole tree.
lg
log base two of how many times you halve a number to reach 1. lg 1,024 = 10.
2
two times the price of the red slack from Chapter 1.
In plain words

Add 1 to the key count n. Take log base two. Double it. The height h never passes that number.

With numbers

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.

The root of a red-black tree has black-height 4. What is the fewest keys the tree can hold?

Chapter 3

Rotations

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.

Rotate one edge

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.

Say it aloud

Alpha is less than x, less than beta, less than y, less than gamma.

α
alpha every key in x's left subtree.
x
x the lower key of the rotating edge.
β
beta every key between x and y: y's left subtree before, x's right subtree after.
y
y the higher key of the rotating edge.
γ
gamma every key in y's right subtree.
In plain words

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 numbers

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.

In a left rotation at x with right child y, which subtree changes its parent?

Chapter 4

Insertion: Add Red, Then Repair

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.

CaseWhenDoThen
1uncle u is redpaint p and u black, g redset z = g and check again, two levels up
2u is black, z is innerrotate at p, away from z's sidez is now outer: go to case 3
3u is black, z is outerpaint p black, g red, rotate at g toward udone

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.

Step an insertion

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.

Why does insertion colour the new key red?

Chapter 5

Deletion: The Missing Black

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.

CaseWhen (x is a left child)DoThen
1w is redw black, parent red, rotate at parent toward xx has a black sibling now: case 2, 3 or 4
2w black, both its children blackpaint w redthe extra black moves up to the parent
3w black, near child red, far child blackswap colours of w and near child, rotate at w away from xthe far child is red: case 4
4w black, far child redw takes the parent's colour, parent and far child black, rotate at parent toward xdone

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.

Delete and repay the black

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.

What is the most rotations one red-black deletion can do?

Chapter 6

The Same Tree as a 2-3-4 Tree

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.

Say it aloud

k equals one plus r.

k
k the keys in one 2-3-4 node: 1, 2 or 3. The node has k + 1 children.
1
one the black key at the centre of the node.
r
r how many red children that black key has: 0, 1 or 2.
In plain words

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.

With numbers

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.

Switch the view

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.

12

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.

In the 2-3-4 view, what does rule 5 (equal black counts on every path) become?

Chapter 7

The Playground

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).

Build any tree you like

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.

TryWhat you should see
Insert 1 to 159 rotations; height 6 against a bound of 8; a plain BST would be 15 deep
Black-heights onboth children of every key show the same number
Delete root, three timesthe successor moves up; the checker stays green
Insert 5 random, many timesabout 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.

You insert 1 to 15 in order. The playground shows height 6. What does the bound 2 lg(n + 1) allow?

Chapter 8

Red-Black Against AVL, and Where Each Lives

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.

Say it aloud

h is less than one point four four times log base two of n plus two, minus zero point three three.

h
h the height of an AVL tree, in keys on the longest path.
n
n the number of keys.
lg
log base two of the number of halvings from a number down to 1.
1.44
one point four four 1 divided by lg of the golden ratio. The thinnest AVL trees grow like Fibonacci numbers.
0.33
zero point three three a small fixed offset from the same Fibonacci count.
In plain words

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.

With numbers

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.

Race AVL and red-black

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.

31

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.

WhereWhat it storesWhy an ordered tree
Java TreeMap, TreeSetsorted maps and setsrange views like headMap need order; the docs name it a red-black tree
C++ std::map (libstdc++)ordered containersthe standard asks for log-time insert, erase and find
Linux kernel rbtreethe scheduler's runnable tasks, epoll's watched filesfast insert, delete by key, and the leftmost (smallest) entry
Nginxconnection timersthe 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.

An index is built once and then read millions of times. Which tree fits better, and why?

Chapter 9

The Field Guide

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 numberMeaning
black-height bh(x)black nodes from x down to a NIL, NIL counted, x not
b ≤ ℓ ≤ 2bevery root-to-NIL path is between b and 2b keys long
s(x) ≥ 2bh(x) − 1a 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 rotationsper insert; case 1 may recolour up the tree
≤ 3 rotationsper delete; case 2 may climb without rotating
about 0.58rotations per insert on random keys (this page's code)
k = 1 + rkeys in the 2-3-4 node of a black key with r red children
h < 1.44 lg(n + 2) − 0.33AVL height: 28 levels at a million keys

Before you trust your tree

  1. Use one black sentinel for every NIL, and set its parent in delete.
  2. Colour new keys red; paint the root black at the end of every fix-up.
  3. Write each mirror branch by swapping left and right everywhere.
  4. Test with a checker that returns black-heights, after ascending, descending and random inserts and after every delete.
  5. Ask whether you need order at all; if not, use a hash table.

The core

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

Keep going

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).

The takeaway. Colour rules turn a global promise, short paths everywhere, into local repairs: a recolour that may climb, and at most a few rotations.

Explain it back with Present or Teach, or go back to the hero and predict the red-black height before you drag the keys.

Red-Black Trees, CLRS Chapter 13
Back to Gleams