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 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
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:
Children of a cluster. The children of a red node are black (or NIL), so a cluster with keys has exactly child clusters or NILs, each holding the keys between two consecutive keys of the cluster:
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.
Conversely, the drawings above obey every red-black rule, and only a 3-node offers a choice, so a 2-3-4 tree with 3-nodes has exactly red-black encodings:
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: . 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 keys has at most 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 . It explains every rebalancing case too.
Insertion: splitting 4-nodes with colors
Insert the key as a red leaf ; in the 2-3-4 view, the key joins an existing leaf cluster. If '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 's uncle, the sibling of its parent. The mirror-image cases swap left and right.
| Case | Condition | Action | 2-3-4 meaning |
|---|---|---|---|
| 1 | The uncle is red | Color the parent and the uncle black and the grandparent red; continue from the grandparent | The cluster was a 4-node: split it and send its middle key up |
| 2 | The uncle is black and is an inner child | Rotate at the parent so that becomes an outer child, then apply case 3 | A 3-node receives its new key in the middle: re-draw it |
| 3 | The uncle is black and is an outer child | Rotate at the grandparent, swap the colors of the parent and the grandparent, stop | The 3-node becomes a 4-node, drawn as a black node with two red children |
Loop invariant (CLRS): at the start of each iteration is red, and at most one rule is broken: either the root is red (when is the root) or and its parent are both red.
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 disappears, but one may appear between the now red grandparent and its parent, two levels up, so the invariant holds again with set to the grandparent:
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:
Termination. Case 1 climbs two levels each time, so the loop runs 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 carries an extra black, a "double black", which the fixup (CLRS's RB-DELETE-FIXUP) pushes up or resolves by looking at 's sibling . The mirror-image cases swap left and right.
| Case | Condition | Action | 2-3-4 meaning |
|---|---|---|---|
| 1 | The sibling is red | Rotate at the parent and swap the colors of and the parent; now has a black sibling, so go on to case 2, 3 or 4 | Re-draw the parent's 3-node so that the cluster beside is a black node |
| 2 | is black with two black children | Color red and move the extra black up to the parent | Merge: the underfull node fuses with its 2-node sibling and a key from the parent, which may underflow in turn |
| 3 | is black, its near child red and its far child black | Rotate at and swap the colors of and that child, turning this into case 4 | Re-draw the sibling's 3-node so that it leans away from |
| 4 | is black and its far child is red | Rotate at the parent, recolor, and stop | Transfer: borrow a key from a 3- or 4-node sibling through the parent |
Why does the deletion fixup perform at most three rotations?
- Each of the four cases rotates at most once, and the loop runs at most three times
- 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
- Deletion only ever rotates at the root
- 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 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.
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 rootThree 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 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 times. Andersson's AA trees (1993) apply the same simplification with the red links leaning right.
Insertion's case 1 is a 4-node split and deletion's case 2 is a merge; everything else costs 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:
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:
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:
The first change at the bottom of an update raises by at most 2, a final transfer changes it by , and every split or merge pays for itself. Since 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, -trees have amortized restructuring when , which holds for 2-3-4 trees (, ) but not for 2-3 trees ().
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 3-nodes has 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: in one insertion in the worst case.
- Bottom-up red-black trees make amortized recolorings because 2-3-4 trees are -trees with ; 2-3 trees, with , 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.
In the 2-3-4 view, what is a black node with two red children?
- A 2-node holding one key
- A 3-node holding two keys
- A 4-node holding three keys
- 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.
During the insertion fixup, and its parent are red and 's uncle is red. What happens?
- Rotate at the grandparent and stop
- Color the parent and the uncle black and the grandparent red, then continue from the grandparent
- Rotate at the parent, then at the grandparent
- 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.
Which statement about left-leaning red-black trees is true?
- They guarantee a smaller height than classic red-black trees
- Their code is shorter, but a single insertion can perform rotations, while a classic insertion never needs more than 2
- They need no color bits
- Classic red-black insertion needs rotations, which the left-leaning version reduces to 2
Show the answer
B. Their code is shorter, but a single insertion can perform 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.
Why are recolorings amortized in red-black trees, while 2-3 trees can be forced to restructure up to the root on every operation?
- Red-black trees store more bits per node
- 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
- 2-3 trees are taller than red-black trees
- 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 and .
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.