Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Red-Black Trees & 2-3-4 Trees

The correspondence, insertion and deletion cases, and left-leaning variants.

A red-black tree is a 2-3-4 tree in disguise. Glue each black node to its red children and you get nodes with 2, 3 or 4 children, all leaves at the same depth. Every case of the famously fiddly insertion and deletion code is a 2-3-4 operation (a split, a transfer or a merge) written in the language of colors and rotations.

What you’ll learn

  • Prove the correspondence between red-black trees and 2-3-4 trees, and count the red-black encodings of a 2-3-4 tree.
  • Prove that insertion's fixup restores every rule with at most two rotations, and explain deletion's four double-black cases with at most three rotations.
  • Compare left-leaning red-black trees with classic ones: code size, rotations per update, and the 2-3 versus 2-3-4 choice.
  • Prove that bottom-up red-black trees need only O(1)O(1) amortized recolorings, with a potential on 2-3-4 node degrees, and explain why 2-3 trees lack this property.

Red-black trees are 2-3-4 trees

DerivationProof
  1. black node+{0,1,2} red children ⟼ a node with 1,2 or 3 keys\text{black node}+\{0,1,2\}\ \text{red children}\ \longmapsto\ \text{a node with }1,2\text{ or }3\text{ keys}

    Clusters are well defined. A red node never has a red parent, and the root is black, so every red node has a black parent and belongs to exactly one cluster, its parent's. A cluster is a black node with at most two red children, holding 1, 2 or 3 keys in inorder:

  2. k keys ⟹ k+1 childrenk\ \text{keys}\ \Longrightarrow\ k+1\ \text{children}

    Children of a cluster. The children of a red node are black (or NIL), so a cluster with kk keys has exactly k+1k+1 child clusters or NILs, each holding the keys between two consecutive keys of the cluster:

  3. #clusters on any root-to-NIL path=black height of the root\#\text{clusters on any root-to-NIL path}=\text{black height of the root}

    Level leaves. Each step from a cluster to a child cluster passes exactly one black node, so the equal-black-count rule says that every path from the root down to a NIL crosses the same number of clusters: all leaves of the 2-3-4 tree are at the same depth.

  4. #{red-black trees encoding one 2-3-4 tree}=2#3-nodes\#\{\text{red-black trees encoding one 2-3-4 tree}\}=2^{\#\text{3-nodes}}

    Conversely, the drawings above obey every red-black rule, and only a 3-node offers a choice, so a 2-3-4 tree with kk 3-nodes has exactly 2k2^k red-black encodings:

Predict before you look

A 2-3-4 tree has five 3-nodes, plus some 2-nodes and 4-nodes. How many different red-black trees encode it?

Show the answer

32

Each 3-node can be drawn with its red child on the left or on the right, independently of the others, while 2-nodes and 4-nodes have one drawing each: 25=322^5=32. Left-leaning red-black trees remove the choice by always putting the red child on the left.

The correspondence explains the height bound at a glance. A 2-3-4 tree with nn keys has at most log⁡2(n+1)\log_2(n+1) levels, the worst case being all 2-nodes, and each level becomes at most two red-black levels, a black node and possibly a red child: height at most about 2log⁡2(n+1)2\log_2(n+1). It explains every rebalancing case too.

Insertion: splitting 4-nodes with colors

Insert the key as a red leaf zz; in the 2-3-4 view, the key joins an existing leaf cluster. If zz's parent is black, the cluster had room: a 2-node became a 3-node, or a 3-node a 4-node, and nothing else is needed. If the parent is red, two red nodes are adjacent, and the fixup (CLRS's RB-INSERT-FIXUP) looks at zz's uncle, the sibling of its parent. The mirror-image cases swap left and right.

CaseConditionAction2-3-4 meaning
1The uncle is redColor the parent and the uncle black and the grandparent red; continue from the grandparentThe cluster was a 4-node: split it and send its middle key up
2The uncle is black and zz is an inner childRotate at the parent so that zz becomes an outer child, then apply case 3A 3-node receives its new key in the middle: re-draw it
3The uncle is black and zz is an outer childRotate at the grandparent, swap the colors of the parent and the grandparent, stopThe 3-node becomes a 4-node, drawn as a black node with two red children
An inner child is a right child of a left child or a left child of a right child; an outer child is a left child of a left child or a right child of a right child.
DerivationProof
  1. violations ⊆ {the root is red}  or  {z and z.p are both red}\text{violations}\ \subseteq\ \{\text{the root is red}\}\ \ \text{or}\ \ \{z\text{ and }z.p\text{ are both red}\}

    Loop invariant (CLRS): at the start of each iteration zz is red, and at most one rule is broken: either the root is red (when zz is the root) or zz and its parent are both red.

  2. case 1: recolor only,z←z.p.p\text{case 1: recolor only},\quad z\leftarrow z.p.p

    Case 1 keeps every black count: the grandparent was black and hands its black down to both of its children. The red-red violation at zz disappears, but one may appear between the now red grandparent and its parent, two levels up, so the invariant holds again with zz set to the grandparent:

  3. case 2→case 3→stop:≤2 rotations\text{case 2}\to\text{case 3}\to\text{stop}:\quad\le2\ \text{rotations}

    Cases 2 and 3 rotate inside the cluster and recolor so that the black counts through that part of the tree are unchanged and no red node has a red child. The new top of the subtree is black, so the loop ends:

  4. #rotations per insertion≤2,#recolorings per insertion=O(log⁡n)\#\text{rotations per insertion}\le2,\qquad\#\text{recolorings per insertion}=O(\log n)

    Termination. Case 1 climbs two levels each time, so the loop runs O(log⁡n)O(\log n) times. It may end with a red root, which a final line colors black, adding one to every black count at once:

Deletion: the double black

Deletion first removes a node with at most one child; a node with two children is replaced by its successor, as in any BST. If the removed node was red, every rule still holds. If it was black, every path through it has lost a black node. When its replacing child is red, coloring that child black restores the counts. Otherwise the child xx carries an extra black, a "double black", which the fixup (CLRS's RB-DELETE-FIXUP) pushes up or resolves by looking at xx's sibling ww. The mirror-image cases swap left and right.

CaseConditionAction2-3-4 meaning
1The sibling ww is redRotate at the parent and swap the colors of ww and the parent; xx now has a black sibling, so go on to case 2, 3 or 4Re-draw the parent's 3-node so that the cluster beside xx is a black node
2ww is black with two black childrenColor ww red and move the extra black up to the parentMerge: the underfull node fuses with its 2-node sibling and a key from the parent, which may underflow in turn
3ww is black, its near child red and its far child blackRotate at ww and swap the colors of ww and that child, turning this into case 4Re-draw the sibling's 3-node so that it leans away from xx
4ww is black and its far child is redRotate at the parent, recolor, and stopTransfer: borrow a key from a 3- or 4-node sibling through the parent
The near child of ww is the one on xx's side. Only case 2 moves upward, and it never rotates.
Check your understanding

Why does the deletion fixup perform at most three rotations?

  1. Each of the four cases rotates at most once, and the loop runs at most three times
  2. Case 2 never rotates; case 1 rotates once and makes the parent red, so a case 2 right after it ends the loop at once; otherwise cases 3 and 4 finish with one rotation each
  3. Deletion only ever rotates at the root
  4. The height of the tree is at most 3 after a deletion
Show the answer

B. Case 2 never rotates; case 1 rotates once and makes the parent red, so a case 2 right after it ends the loop at once; otherwise cases 3 and 4 finish with one rotation each

Case 2 moves the extra black upward without rotating, possibly many times. Case 1 can happen only once before the loop stops: it makes the parent red, so a following case 2 stops there, and cases 3 and 4 end the loop. That is at most 1+1+1=31+1+1=3 rotations.

Left-leaning trees and amortized recoloring

A left-leaning red-black tree (Sedgewick, 2008) requires every red link to lean left, which gives each 3-node a single drawing. In the version below, the fixes run on the way back up the insertion path, and they encode 2-3 trees; moving the 4-node split to the way down gives 2-3-4 trees instead.

python
class Node:
    def __init__(self, key):
        self.key, self.left, self.right, self.red = key, None, None, True

def is_red(x): return x is not None and x.red

def rotate_left(h):                  # a right-leaning red link now leans left
    x = h.right
    h.right, x.left = x.left, h
    x.red, h.red = h.red, True
    return x

def rotate_right(h):                 # a left-leaning red link now leans right
    x = h.left
    h.left, x.right = x.right, h
    x.red, h.red = h.red, True
    return x

def flip(h):                         # split a temporary 4-node: pass red up
    h.red, h.left.red, h.right.red = True, False, False

def insert(h, key):
    if h is None:
        return Node(key)             # a new key arrives on a red link
    if key < h.key:   h.left = insert(h.left, key)
    elif key > h.key: h.right = insert(h.right, key)
    if is_red(h.right) and not is_red(h.left): h = rotate_left(h)
    if is_red(h.left) and is_red(h.left.left): h = rotate_right(h)
    if is_red(h.left) and is_red(h.right):     flip(h)
    return h

def put(root, key):
    root = insert(root, key)
    root.red = False                 # the root is always black
    return root

Three lines of fixes replace the case analysis. Tested against random keys, checking that no red link leans right, no two reds are adjacent and every path has the same number of black links.

The short code has a price. In a quick experiment with 10510^5 random keys, it made about 1.19 rotations per insertion, twice the 0.58 of CLRS's insertion, and up to 11 in a single insertion, where CLRS never exceeds 2, because the fixes may rotate at every level on the way up. Deletion, which pushes red links down on the way to the key, also rotates O(log⁡n)O(\log n) times. Andersson's AA trees (1993) apply the same simplification with the red links leaning right.

DerivationProof sketch in 2-3-4 terms
  1. ϕ(1)=3,ϕ(2)=1,ϕ(3)=0,ϕ(4)=2,ϕ(5)=4;Φ=∑nodesϕ(children)\phi(1)=3,\quad\phi(2)=1,\quad\phi(3)=0,\quad\phi(4)=2,\quad\phi(5)=4;\qquad\Phi=\sum_{\text{nodes}}\phi(\text{children})

    Insertion's case 1 is a 4-node split and deletion's case 2 is a merge; everything else costs O(1)O(1) per operation. Give each 2-3-4 node a potential that depends on its number of children, allowing a node to hold 5 children just before it splits and 1 child just before it merges:

  2. ΔΦ ≤ ϕ(2)+ϕ(3)−ϕ(5)+2 = 1+0−4+2 = −1\Delta\Phi\ \le\ \phi(2)+\phi(3)-\phi(5)+2\ =\ 1+0-4+2\ =\ -1

    A split turns a 5-child node into a 2-node and a 3-node and gives the parent one more child, which raises the parent's potential by at most 2:

  3. ΔΦ ≤ ϕ(3)−ϕ(1)−ϕ(2)+2 = 0−3−1+2 = −2\Delta\Phi\ \le\ \phi(3)-\phi(1)-\phi(2)+2\ =\ 0-3-1+2\ =\ -2

    A merge fuses a 1-child node with a 2-node sibling into a 3-node, and the parent loses a child, which raises its potential by at most 2:

  4. #splits+#merges ≤ ∑operationsO(1) = O(m)\#\text{splits}+\#\text{merges}\ \le\ \sum_{\text{operations}}O(1)\ =\ O(m)

    The first change at the bottom of an update raises Φ\Phi by at most 2, a final transfer changes it by O(1)O(1), and every split or merge pays for itself. Since Φ≥0\Phi\ge0 and starts at 0:

Think first Why does this argument fail for 2-3 trees, the trees behind the left-leaning code above?

In a 2-3 tree, splitting an overfull node leaves two 2-nodes, each one deletion away from underflow, and a merge produces a full 3-node, one insertion away from overflow, so there is no slack for a potential to collect. An adversary can alternate inserting and deleting one key so that every operation splits or merges all the way up. In a simulation on a random 2-3 tree with 3,000 keys and height 9, some keys forced 18 restructurings per insert–delete pair, cycle after cycle, while the 2-3-4 tree on the same keys settled to none. In general, (a,b)(a,b)-trees have O(1)O(1) amortized restructuring when b≥2ab\ge2a, which holds for 2-3-4 trees (a=2a=2, b=4b=4) but not for 2-3 trees (b=3b=3).

Key takeaways

  • A black node with its red children is one 2-3-4 node, and the black height is the 2-3-4 height; a 2-3-4 tree with kk 3-nodes has 2k2^k red-black encodings.
  • Insertion: case 1 recolors (a 4-node split moving up), and cases 2 and 3 rotate and stop, at most 2 rotations. Deletion: four double-black cases, where merges move up and transfers stop, at most 3 rotations.
  • Left-leaning red-black trees fix the lean of 3-nodes and shorten the code, at the price of more rotations: Θ(log⁡n)\Theta(\log n) in one insertion in the worst case.
  • Bottom-up red-black trees make O(1)O(1) amortized recolorings because 2-3-4 trees are (a,b)(a,b)-trees with b≥2ab\ge2a; 2-3 trees, with b=2a−1b=2a-1, can be forced to split or merge up to the root on every operation.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the 2-3-4 view, what is a black node with two red children?

  1. A 2-node holding one key
  2. A 3-node holding two keys
  3. A 4-node holding three keys
  4. A leaf
Show the answer

C. A 4-node holding three keys

The black node and its two red children form one cluster with three keys and four children: a 4-node.

Question 2

During the insertion fixup, zz and its parent are red and zz's uncle is red. What happens?

  1. Rotate at the grandparent and stop
  2. Color the parent and the uncle black and the grandparent red, then continue from the grandparent
  3. Rotate at the parent, then at the grandparent
  4. Nothing: with a red uncle no rule is broken
Show the answer

B. Color the parent and the uncle black and the grandparent red, then continue from the grandparent

A red uncle means the grandparent's cluster is a 4-node that has just received a fourth key. Recoloring splits it: the middle key, the grandparent, moves up into the cluster above, where it may cause a new red-red violation two levels higher.

Question 3

Which statement about left-leaning red-black trees is true?

  1. They guarantee a smaller height than classic red-black trees
  2. Their code is shorter, but a single insertion can perform Θ(log⁡n)\Theta(\log n) rotations, while a classic insertion never needs more than 2
  3. They need no color bits
  4. Classic red-black insertion needs Θ(log⁡n)\Theta(\log n) rotations, which the left-leaning version reduces to 2
Show the answer

B. Their code is shorter, but a single insertion can perform Θ(log⁡n)\Theta(\log n) rotations, while a classic insertion never needs more than 2

The left-leaning fixes run at every node on the way back up the insertion path, so rotations can occur at many levels in one insertion. Classic bottom-up insertion only recolors while it climbs and rotates at most twice, at the end.

Question 4

Why are recolorings O(1)O(1) amortized in red-black trees, while 2-3 trees can be forced to restructure up to the root on every operation?

  1. Red-black trees store more bits per node
  2. In 2-3-4 trees a split leaves nodes that are neither full nor minimal, so a potential function pays for cascades; in 2-3 trees a split leaves minimal nodes and a merge a full one, so alternating updates can cascade every time
  3. 2-3 trees are taller than red-black trees
  4. Red-black trees never cascade at all
Show the answer

B. In 2-3-4 trees a split leaves nodes that are neither full nor minimal, so a potential function pays for cascades; in 2-3 trees a split leaves minimal nodes and a merge a full one, so alternating updates can cascade every time

After a 2-3-4 split the two halves are a 2-node and a 3-node, and after a merge the node is a 3-node: each restructuring leaves slack that later operations must use up first. In a 2-3 tree the slack is zero, which is the difference between b≥2ab\ge2a and b=2a−1b=2a-1.

Further reading

  • L. J. Guibas & R. Sedgewick, "A dichromatic framework for balanced trees," Proceedings of the 19th IEEE Symposium on Foundations of Computer Science (1978), 8–21.
  • R. Bayer, "Symmetric binary B-trees: Data structure and maintenance algorithms," Acta Informatica 1 (1972), 290–306.
  • R. Sedgewick, "Left-leaning red-black trees" (2008), Princeton University.
  • R. E. Tarjan, "Updating a balanced search tree in O(1) rotations," Information Processing Letters 16(5) (1983), 253–257.
  • K. Mehlhorn & P. Sanders, Algorithms and Data Structures: The Basic Toolbox (Springer, 2008), chapter 7.