AlgoFrames

Red-black trees

A red-black tree colours nodes red or black and enforces rules that keep it roughly balanced. Inserts recolor and rotate to fix violations.

Before you start: AVL trees and rotations.

The idea

A red-black tree is a search tree whose nodes are coloured red or black. The colours keep the tree from leaning.

A plain search tree can turn into a chain. Three colour rules keep a red-black tree within twice the ideal height.

Intuition

Rule 1: the root is black. Rule 2: a red node never has a red child.

Without rule 2, a long run of red nodes could hide a long path.

Rule 3: every path from the root down to an empty spot holds the same number of black nodes.

Red nodes cannot sit side by side. So the longest path is at most twice the shortest.

Both paths hold 2 black nodes. The shortest is all black; the longest alternates black and red.

The code

Back to the tree 10, 20, 30. Here is the same fix-up, line by line in the code.

Complexity

A red-black tree with n keys has height at most 2 log2(n + 1). Search, insert and delete cost O(log n).

Insert walks down one path, then the fix-up climbs back up. It makes at most two rotations and O(log n) recolours.

Pitfalls

Adding 30 under red 20: its uncle is 10's empty left spot (drawn nil). An empty spot counts as black, so a rotation is needed.

Making the parent black alone adds a black node to one side only. Rule 3 then fails.

Variations

Delete uses the same recolours and rotations. Java's TreeMap is a red-black tree.

Code

Pseudocode

z ← new red leaf, placed as in a BST
while z.parent is red
  p ← z.parent, g ← p.parent
  uncle ← the other child of g
  if uncle is red
    p ← black, uncle ← black, g ← red
    z ← g
  else
    if z is an inner grandchild of g
      rotate z above p, then swap the roles of z and p
    rotate p above g
    p ← black, g ← red, stop
root ← black

Python

def fix_insert(tree, z):
    while z.parent is not None and z.parent.red:
        p = z.parent
        g = p.parent
        uncle = g.right if p is g.left else g.left
        if uncle is not None and uncle.red:
            p.red = False
            uncle.red = False
            g.red = True
            z = g
        else:
            if (z is p.right) == (p is g.left):
                rotate_up(tree, z)
                z, p = p, z
            rotate_up(tree, p)
            p.red = False
            g.red = True
            break
    tree.root.red = False

JavaScript

function fixInsert(tree, z) {
  while (z.parent !== null && z.parent.red) {
    let p = z.parent;
    const g = p.parent;
    const uncle = p === g.left ? g.right : g.left;
    if (uncle !== null && uncle.red) {
      p.red = false;
      uncle.red = false;
      g.red = true;
      z = g;
    } else {
      if ((z === p.right) === (p === g.left)) {
        rotateUp(tree, z);
        [z, p] = [p, z];
      }
      rotateUp(tree, p);
      p.red = false;
      g.red = true;
      break;
    }
  }
  tree.root.red = false;
}

Cost at a glance

AccessO(log n)
SearchO(log n)
InsertO(log n)
DeleteO(log n)
SpaceO(n)

Practice problems (4)

Fix a violation Warm-up

A red-black tree holds 10 (black) and 5 (red). Insert 3. It becomes a red left child of 5, so 5 and 3 are both red. The uncle of 3 is empty, which counts as black. Which tree is the correct result?

Match the case to its fix Warm-up

A new red node is inserted. Match each situation to the step that fixes it.

Valid colorings Standard

Follow the check of this colouring against the three rules of a red-black tree. Answer each question before the step plays.

Black height Standard

The black height of a tree is the number of black nodes on a path from the root down to an empty spot. The root counts. In a valid tree every such path agrees. Follow the check and answer each question.

Related topics

Next on the path: Ordered sets and maps: floor, ceiling, range queries