function insert(tree: Tree, key: number) {const node = bstInsert(tree, key); // new nodes are red
fixUp(tree, node);
}
function fixUp(tree: Tree, node: Node) { while (node.parent?.color === "red") {const parent = node.parent, grandparent = parent.parent!;
const uncle = parent === grandparent.left ? grandparent.right : grandparent.left;
if (uncle?.color === "red") {parent.color = uncle.color = "black";
grandparent.color = "red";
node = grandparent;
continue;
}
if (node === parent.right && parent === grandparent.left) { rotateLeft(tree, parent); node = parent; } else if (node === parent.left && parent === grandparent.right) { rotateRight(tree, parent); node = parent; }node.parent!.color = "black";
grandparent.color = "red";
if (node === node.parent!.left) rotateRight(tree, grandparent); else rotateLeft(tree, grandparent);
}
tree.root!.color = "black";
}
The tree is empty: 24 becomes the root and is painted black.
Understanding Red-black tree
The idea
A red-black tree is a binary search tree where every node is red or black, the root is black, a red node never has a red child, and every path from the root to a leaf passes the same number of black nodes. Those rules force the longest path to be at most twice the shortest, so the height stays within 2 log₂ n.
A new node is inserted as a red leaf, which keeps the black count intact but may put two reds in a row. The fix-up looks at the uncle: if it is red, recolour parent, uncle and grandparent and move the problem two levels up; if it is black, one or two rotations plus a recolour fix it for good. Insertion therefore costs at most two rotations.
The four stages
Complexity
Versus its siblings
Pseudocode
INSERT(tree, key)
node ← BST insert, coloured red
while parent(node) is red
if uncle(node) is red: paint parent and uncle black, grandparent red; node ← grandparent
else: if node is an inner grandchild, rotate parent outward; paint parent black, grandparent red; rotate grandparent
paint root black
When to use
Pitfalls
History
Rudolf Bayer invented the structure in 1972 as symmetric binary B-trees, a binary encoding of 2-3-4 trees. Leonidas Guibas and Robert Sedgewick gave it the red and black colours in 1978, chosen, Sedgewick says, because those were the pens that printed best on the laser printer at Xerox PARC.