Lesson 12 · Non-linear structures

Red-Black Trees

A red-black tree is a binary search tree with one colour bit per node. Five colouring rules keep the longest path at most twice the shortest, so search, insert and delete stay O(log n), and a repair needs at most two or three rotations.

Red-Black Trees concept diagramA visual explanation of the layout and operations shown in this lesson.after inserting 10, 20, 30 — the middle key becomes a black root201030no red node may have a red parent, and the root is always blackevery root-to-leaf path crosses the same number of black nodes
1

The Five Rules

  1. Every node is red or black
  2. The root is black
  3. Every empty child position (NIL leaf) counts as black
  4. A red node never has a red child
  5. Every path from a node down to a NIL leaf passes the same number of black nodes

A red black tree, often shortened to RB tree, is a binary search tree where each node also stores one bit: its colour. The five red black tree rules above limit how colours may be arranged, and that alone keeps the tree close to balanced without storing any heights.

Rules 4 and 5 do the real work. Rule 5 defines the black height of a node: the number of black nodes on any path from it down to a leaf, not counting the node itself. Rule 4 limits how many red nodes can be squeezed between them.

Implementations often use a single shared NIL sentinel node, coloured black, instead of null pointers. Every real node then has two real children, so the repair code can read a child's colour without checking for null first.

The invariant is looser than an AVL tree's, which caps the height difference at every node. A looser rule is broken less often and fixed more cheaply, and that is the point of the design.

  • Rules 1 to 3 are conventions; rules 4 and 5 bound the height
  • Black height counts black nodes below a node, down to the NIL leaves
  • A tree with only black nodes is valid only if it is perfectly balanced
2

Why the Height Stays Within 2 log n

Take any node with black height bh. The shortest path down from it is all black: bh nodes. Because no two reds can be next to each other, the longest path can at most alternate red and black: 2 × bh nodes. So no path is more than twice as long as any other.

Counting nodes gives the bound. A subtree with black height bh holds at least 2^bh − 1 nodes, so bh ≤ log₂(n + 1), and since the root's height is at most 2 × bh, the height is at most 2 log₂(n + 1). Search, insert and delete are all O(log n) in the worst case.

For a million keys that means at most 39 levels. An AVL tree of the same size stays under about 28, and a perfectly balanced tree needs 20. Every lookup here may pay a few more comparisons; the next section shows what it gets back.

  • Shortest path: all black; longest: red and black alternating
  • At least 2^bh − 1 nodes below a node with black height bh
  • Height ≤ 2 log₂(n + 1); AVL ≤ about 1.44 log₂ n
3

Insertion: Recolour or Rotate

  1. Insert the key as in a plain BST and colour it red
  2. If its parent is black, stop: no rule is broken
  3. Parent red and uncle red: make parent and uncle black, grandparent red, then repeat the check from the grandparent
  4. Parent red and uncle black, node on the inside (zigzag): rotate the parent so the three nodes form a straight line
  5. Parent red and uncle black, straight line: rotate the grandparent, swap the colours of parent and grandparent, stop
  6. Finally, colour the root black

Red black tree insertion always adds the new node red. A red node changes no path's black count, so rule 5 cannot break; only rule 4 can, if the parent is also red. That is the easier rule to repair.

The repair depends on the uncle, the parent's sibling. A red uncle means the grandparent has two red children, so pushing the black down one level (parent and uncle black, grandparent red) fixes both sides without moving anything. The grandparent may now sit under a red node, so the check repeats two levels higher.

A black uncle (a NIL leaf counts) means recolouring cannot balance the sides, so a rotation is needed: one when the new node, parent and grandparent form a straight line, two when they zigzag, just like AVL's single and double rotations. After a rotation the subtree's top is black again and the repair stops.

So an insert does at most two rotations, and the recolouring that climbs the tree only flips bits. The walk-through below inserts 10, 5, 15, 1, 0, 3, 4 and meets every case once.

  • New nodes are red so that rule 5 is never broken by an insert
  • Red uncle: recolour and move up, no pointers change
  • Black uncle: rotate once (line) or twice (zigzag) and stop
  • The root may turn red during recolouring; the last step makes it black
Key reference

Terms, operations, and practical uses

Colour rules

  • Root ruleThe root is always black; the last step of every insert repaints it.
  • Red ruleA red node has only black children, so reds never sit next to each other on a path.
  • Black heightEvery path from a node to its NIL leaves has the same number of black nodes.

Insert repair

  • Insert redA red node adds no black to any path, so only the red rule can break.
  • Red uncleRecolour parent and uncle black, grandparent red, and check again from the grandparent.
  • Black uncleRotate once if the three nodes form a line, twice if they zigzag, then stop.

In practice

  • Height boundAt most 2 log₂(n + 1): the longest path is at most twice the shortest.
  • Rotation boundAt most 2 per insert and 3 per delete, which keeps writes predictable.
  • LibrariesC++ std::map, Java TreeMap, Java HashMap's large buckets, Linux kernel timers and scheduler.
Implementation

Code in Python, C++ and Java

RED, BLACK = "R", "B"


class Node:
    def __init__(self, key):
        self.key = key
        self.color = RED            # every new node starts red
        self.left = self.right = self.parent = None


def color(node):
    return node.color if node else BLACK   # empty children count as black


class RedBlackTree:
    def __init__(self):
        self.root = None

    def rotate_left(self, x):
        y = x.right
        x.right = y.left
        if y.left:
            y.left.parent = x
        self.replace(x, y)
        y.left = x
        x.parent = y

    def rotate_right(self, x):
        y = x.left
        x.left = y.right
        if y.right:
            y.right.parent = x
        self.replace(x, y)
        y.right = x
        x.parent = y

    def replace(self, old, new):
        new.parent = old.parent
        if old.parent is None:
            self.root = new
        elif old is old.parent.left:
            old.parent.left = new
        else:
            old.parent.right = new

    def insert(self, key):
        node, parent, cur = Node(key), None, self.root
        while cur:
            parent = cur
            cur = cur.left if key < cur.key else cur.right
        node.parent = parent
        if parent is None:
            self.root = node
        elif key < parent.key:
            parent.left = node
        else:
            parent.right = node
        self.fix(node)

    def fix(self, z):
        while color(z.parent) == RED:
            p = z.parent
            g = p.parent
            if p is g.left:
                uncle = g.right
                if color(uncle) == RED:          # red uncle: recolour, move up
                    p.color = uncle.color = BLACK
                    g.color = RED
                    z = g
                    continue
                if z is p.right:                 # zigzag: turn it into a line
                    self.rotate_left(p)
                    z, p = p, z
                self.rotate_right(g)             # line: one rotation ends it
            else:
                uncle = g.left
                if color(uncle) == RED:
                    p.color = uncle.color = BLACK
                    g.color = RED
                    z = g
                    continue
                if z is p.left:
                    self.rotate_right(p)
                    z, p = p, z
                self.rotate_left(g)
            p.color, g.color = BLACK, RED
        self.root.color = BLACK


def preorder(node):
    if not node:
        return []
    return [f"{node.key}{node.color}"] + preorder(node.left) + preorder(node.right)


def black_height(node):
    if not node:
        return 0
    left, right = black_height(node.left), black_height(node.right)
    if left < 0 or left != right:
        return -1                                 # -1 marks a broken tree
    if node.color == RED and RED in (color(node.left), color(node.right)):
        return -1
    return left + (node.color == BLACK)


tree = RedBlackTree()
for key in [10, 5, 15, 1, 0, 3, 4]:
    tree.insert(key)
print("preorder:", " ".join(preorder(tree.root)))
print("black nodes on every path:", black_height(tree.root))
#include <iostream>
#include <string>
using namespace std;

enum Color { RED, BLACK };

struct Node {
    int key;
    Color color = RED;   // every new node starts red
    Node *left = nullptr, *right = nullptr, *parent = nullptr;
    Node(int k) : key(k) {}
};

Color color(Node* n) { return n ? n->color : BLACK; }   // empty children count as black

struct RedBlackTree {
    Node* root = nullptr;

    void replace(Node* old, Node* now) {
        now->parent = old->parent;
        if (!old->parent) root = now;
        else if (old == old->parent->left) old->parent->left = now;
        else old->parent->right = now;
    }

    void rotateLeft(Node* x) {
        Node* y = x->right;
        x->right = y->left;
        if (y->left) y->left->parent = x;
        replace(x, y);
        y->left = x;
        x->parent = y;
    }

    void rotateRight(Node* x) {
        Node* y = x->left;
        x->left = y->right;
        if (y->right) y->right->parent = x;
        replace(x, y);
        y->right = x;
        x->parent = y;
    }

    void insert(int key) {
        Node* node = new Node(key);
        Node *parent = nullptr, *cur = root;
        while (cur) {
            parent = cur;
            cur = key < cur->key ? cur->left : cur->right;
        }
        node->parent = parent;
        if (!parent) root = node;
        else if (key < parent->key) parent->left = node;
        else parent->right = node;
        fix(node);
    }

    void fix(Node* z) {
        while (color(z->parent) == RED) {
            Node* p = z->parent;
            Node* g = p->parent;
            if (p == g->left) {
                Node* uncle = g->right;
                if (color(uncle) == RED) {        // red uncle: recolour, move up
                    p->color = uncle->color = BLACK;
                    g->color = RED;
                    z = g;
                    continue;
                }
                if (z == p->right) {              // zigzag: turn it into a line
                    rotateLeft(p);
                    swap(z, p);
                }
                rotateRight(g);                   // line: one rotation ends it
            } else {
                Node* uncle = g->left;
                if (color(uncle) == RED) {
                    p->color = uncle->color = BLACK;
                    g->color = RED;
                    z = g;
                    continue;
                }
                if (z == p->left) {
                    rotateRight(p);
                    swap(z, p);
                }
                rotateLeft(g);
            }
            p->color = BLACK;
            g->color = RED;
        }
        root->color = BLACK;
    }
};

void preorder(Node* n, string& out) {
    if (!n) return;
    out += (out.empty() ? "" : " ") + to_string(n->key) + (n->color == RED ? "R" : "B");
    preorder(n->left, out);
    preorder(n->right, out);
}

int blackHeight(Node* n) {
    if (!n) return 0;
    int left = blackHeight(n->left), right = blackHeight(n->right);
    if (left < 0 || left != right) return -1;   // -1 marks a broken tree
    if (n->color == RED && (color(n->left) == RED || color(n->right) == RED)) return -1;
    return left + (n->color == BLACK);
}

int main() {
    RedBlackTree tree;
    for (int key : {10, 5, 15, 1, 0, 3, 4}) tree.insert(key);
    string out;
    preorder(tree.root, out);
    cout << "preorder: " << out << '\n';
    cout << "black nodes on every path: " << blackHeight(tree.root) << '\n';
}
public class Main {
    static final boolean RED = true, BLACK = false;

    static class Node {
        int key;
        boolean color = RED;   // every new node starts red
        Node left, right, parent;
        Node(int key) { this.key = key; }
    }

    static boolean color(Node n) { return n == null ? BLACK : n.color; }   // empty children count as black

    static class RedBlackTree {
        Node root;

        void replace(Node old, Node now) {
            now.parent = old.parent;
            if (old.parent == null) root = now;
            else if (old == old.parent.left) old.parent.left = now;
            else old.parent.right = now;
        }

        void rotateLeft(Node x) {
            Node y = x.right;
            x.right = y.left;
            if (y.left != null) y.left.parent = x;
            replace(x, y);
            y.left = x;
            x.parent = y;
        }

        void rotateRight(Node x) {
            Node y = x.left;
            x.left = y.right;
            if (y.right != null) y.right.parent = x;
            replace(x, y);
            y.right = x;
            x.parent = y;
        }

        void insert(int key) {
            Node node = new Node(key), parent = null, cur = root;
            while (cur != null) {
                parent = cur;
                cur = key < cur.key ? cur.left : cur.right;
            }
            node.parent = parent;
            if (parent == null) root = node;
            else if (key < parent.key) parent.left = node;
            else parent.right = node;
            fix(node);
        }

        void fix(Node z) {
            while (color(z.parent) == RED) {
                Node p = z.parent, g = p.parent;
                if (p == g.left) {
                    Node uncle = g.right;
                    if (color(uncle) == RED) {        // red uncle: recolour, move up
                        p.color = uncle.color = BLACK;
                        g.color = RED;
                        z = g;
                        continue;
                    }
                    if (z == p.right) {               // zigzag: turn it into a line
                        rotateLeft(p);
                        Node t = z; z = p; p = t;
                    }
                    rotateRight(g);                   // line: one rotation ends it
                } else {
                    Node uncle = g.left;
                    if (color(uncle) == RED) {
                        p.color = uncle.color = BLACK;
                        g.color = RED;
                        z = g;
                        continue;
                    }
                    if (z == p.left) {
                        rotateRight(p);
                        Node t = z; z = p; p = t;
                    }
                    rotateLeft(g);
                }
                p.color = BLACK;
                g.color = RED;
            }
            root.color = BLACK;
        }
    }

    static void preorder(Node n, StringBuilder out) {
        if (n == null) return;
        if (out.length() > 0) out.append(' ');
        out.append(n.key).append(n.color == RED ? "R" : "B");
        preorder(n.left, out);
        preorder(n.right, out);
    }

    static int blackHeight(Node n) {
        if (n == null) return 0;
        int left = blackHeight(n.left), right = blackHeight(n.right);
        if (left < 0 || left != right) return -1;   // -1 marks a broken tree
        if (n.color == RED && (color(n.left) == RED || color(n.right) == RED)) return -1;
        return left + (n.color == BLACK ? 1 : 0);
    }

    public static void main(String[] args) {
        RedBlackTree tree = new RedBlackTree();
        for (int key : new int[]{10, 5, 15, 1, 0, 3, 4}) tree.insert(key);
        StringBuilder out = new StringBuilder();
        preorder(tree.root, out);
        System.out.println("preorder: " + out);
        System.out.println("black nodes on every path: " + blackHeight(tree.root));
    }
}
Watch it run

Step through it

Running on insert 10, 5, 15, 1, 0, 3, 4

insert 10blackred10new node: red → it is the root → blackblack height of every path: 1
Step 1

Insert 10: the root is painted black

Every new node starts red. 10 is the first key, so it becomes the root, and the root must be black (rule 2). The last line of every insert repaints it.

Output
1 / 15
4

Deletion in Brief

Deleting a red node never breaks a rule. Deleting a black node leaves one path a black node short, and the fix treats the spot as carrying an extra double black that must be pushed up the tree or absorbed.

The cases look at the sibling of the double-black spot. A red sibling is rotated over so the sibling becomes black. A black sibling with two black children is recoloured red and the problem moves up one level. A black sibling with a red child gets one or two rotations, and the extra black is absorbed for good.

Like insertion, the climbing case only recolours, so deletion does at most three rotations. It has more cases than insertion and is the part most people look up rather than write from memory; library code is the safer choice in practice.

  • Removing a red node, or a black node with one red child, is simple
  • Otherwise the hole becomes double black and the sibling decides the fix
  • At most 3 rotations per delete; AVL may rotate at every level
5

AVL vs Red Black Tree

The choice between an AVL tree and a red-black tree comes down to the mix of reads and writes. AVL's shorter tree makes lookups slightly faster; red-black's cheaper deletes make updates faster. A general-purpose library cannot know its workload, so it takes the structure whose worst write is cheapest.

That is why the red black tree data structure sits behind C++'s std::map and std::set, Java's TreeMap and TreeSet, and the overflow buckets of Java's HashMap (a bucket's chain becomes a tree once it grows past 8 entries in a table of at least 64 buckets). The Linux kernel uses it for timers and for the scheduler's run queue, the completely fair scheduler and its successor. It packs the colour into the low bit of the parent pointer, so the colour costs no memory at all.

Compared with a hash table, the tree keeps keys in order: sorted iteration, range scans, and floor or ceiling lookups ('the largest key not above x') that hashing cannot answer. That is why C++ has both std::map and std::unordered_map.

The structure is also a binary encoding of a 2-3-4 tree, a B-tree of order 4: a black node plus its red children is one node holding up to three keys. Splitting a full 4-node is exactly the red-uncle recolour. Sedgewick's left-leaning variant allows red links only on the left and cuts the number of cases roughly in half.

Two self-balancing BSTs side by side
AVL treeRed-black tree
Balance ruleSubtree heights differ by at most 1Colour rules; longest path at most twice the shortest
Worst heightAbout 1.44 log₂ n2 log₂(n + 1)
Rotations per insertAt most 2At most 2
Rotations per deleteUp to O(log n)At most 3
Extra data per nodeHeight or balance factorOne colour bit
Found inRead-heavy indexes, some databasesstd::map, TreeMap, the Linux kernel
  • Lookup-heavy and rarely changed: AVL
  • Mixed or write-heavy, or unknown: red-black
  • Need keys in order: either tree beats a hash table
  • A 2-3-4 tree drawn with binary nodes gives the same shape