red-black BST2-3 tree1def fix(h):2 if red(h.right) and not red(h.left):3 h = rotate_left(h)4 if red(h.left) and red(h.left.left):5 h = rotate_right(h)6 if red(h.left) and red(h.right):7 flip_colors(h)8 return hkeyheight123456712345675
Nodes: one key each; the dot and the link from the parent are red or blackTrays: one 2-3 node, holding one or two keysCode card: the line that just ranLeft: a left-leaning red-black tree, each node in the column of its key, so a rotation only slides nodes up or down. Right: the 2-3 tree it stands for, one tray per 2-3 node. Glue the nodes joined by red links together and you get the 2-3 tree. A colour flip is a 2-3 split, and the tree only grows at the top, so every leaf stays at the same depth.

Two drawings of one tree

  1. On the right is a 2-3 tree; on the left, a red-black tree that stores the same keys. Insert 1: both hold one node. A new red-black node always starts red, then the root is painted black.

Why it stays balanced

Code and cost

What happens

;; step 1/10 · One key, two drawings
insert 1 (* = red node, its link from the parent is red)
  insert 1          1*
  root 1 turns black1

2-3 tree: [1]
height: 0

This lesson uses the left-leaning red-black tree of Sedgewick and Wayne (Algorithms, §3.3), which matches 2-3 trees one to one. Classic red-black trees (CLRS chapter 13) also allow red links that lean right; they match 2-3-4 trees instead. The guarantees are the same. Books colour either the links or the nodes. They mean the same thing: a node is red when the link from its parent is red. The figure shows both: the link colour, and a dot on each node.