Red-Black Properties and the Height Bound
A plain BST is only as good as its height, and its height depends on the order of the operations. A balanced search tree adds rules that force the height to stay whatever happens, and repairs the tree after every insertion and deletion. The red-black tree is the most widely used balanced tree: std::map and std::set in the major C++ libraries, Java's TreeMap, and many parts of the Linux kernel, including its CPU scheduler, are built on it.
The idea is to colour every node red or black and to constrain the colours so that no root-to-leaf path can be more than twice as long as any other. This lesson states the rules, proves that they imply height at most , and builds a checker that the next lessons use after every operation. The AVL Trees lesson in the DSA course shows another balancing scheme, with stricter rules and more rotations.
The five properties
A red-black tree is a BST in which each node has an extra field, its colour, and every missing child is represented by a NIL leaf. The keys sit in the internal nodes; the NIL leaves hold nothing. The tree satisfies:
- Every node is either red or black.
- The root is black.
- Every leaf (NIL) is black.
- A red node has two black children. (No red node has a red parent.)
- For every node, all simple paths from it down to the leaves of its subtree contain the same number of black nodes.
Implementations use one shared sentinel node for all the NIL leaves, and for the root's parent: it is black, and its other fields are never relied on. That keeps the code free of special cases, as the sentinel did for linked lists.
The black-height of a node is the number of black nodes on any path from down to a leaf, not counting itself but counting the NIL leaf. Property 5 is exactly what makes this well defined. The black-height of the tree is of its root.
A checker
The checker walks the tree, verifies the order and the colour rules, and returns the black-height of each subtree, failing if the two sides of some node disagree. It runs in time. Trees are written as nested tuples (key, colour, left, right) with None for NIL; the three examples are a valid tree, a tree with a red node under a red node, and a tree whose paths have different numbers of black nodes.
def check_rb(tree):
"""returns the black-height of a red-black tree given as nested (key, colour, left, right) tuples"""
def walk(x, lo, hi):
if x is None:
return 1 # a NIL leaf: black, property 3
key, colour, left, right = x
assert colour in ("R", "B"), "property 1"
assert (lo is None or lo < key) and (hi is None or key < hi), "BST order"
if colour == "R":
for c in (left, right):
assert c is None or c[1] == "B", f"property 4: red {key} has a red child"
bl, br = walk(left, lo, key), walk(right, key, hi)
assert bl == br, f"property 5: black counts {bl} and {br} below {key}"
return bl + (colour == "B")
assert tree is None or tree[1] == "B", "property 2"
return walk(tree, None, None) - 1 # bh does not count the root itself
good = (26, "B", (17, "R", (14, "B", (10, "R", None, None), None), (21, "B", None, None)),
(41, "B", (30, "R", None, None), (47, "R", None, None)))
red_red = (26, "B", (17, "R", (14, "R", None, None), (21, "B", None, None)), (41, "B", None, None))
uneven = (26, "B", (17, "B", None, None), (41, "B", (30, "B", None, None), None))
for name, t in [("good", good), ("red_red", red_red), ("uneven", uneven)]:
try:
print(f"{name:8}: valid, black-height {check_rb(t)}")
except AssertionError as e:
print(f"{name:8}: invalid, {e}")good : valid, black-height 2
red_red : invalid, property 4: red 17 has a red child
uneven : invalid, property 5: black counts 2 and 1 below 41
In good, every path from the root down meets exactly two black nodes after the root, counting the NIL leaf at its end (14 and NIL on the way to 10, 21 and NIL, 41 and NIL), so the black-height of the root is 2. In uneven, the path from 41 to its right NIL has no black internal node while the path through 30 has one.
In C++
The same checker on an array-based tree, as the later C++ examples will use it: node 0 is the shared black sentinel nil.
#include <cstdio>
#include <stdexcept>
#include <vector>
struct RB {
struct Node { int key; bool red; int left, right; };
std::vector<Node> t{{0, false, 0, 0}}; // t[0] is T.nil, black
int root = 0;
int add(int key, bool red, int l = 0, int r = 0) {
t.push_back({key, red, l, r});
return static_cast<int>(t.size()) - 1;
}
int black_height(int x, long lo, long hi) const { // counts the NIL leaf, not x
if (x == 0) return 0;
const Node& n = t[x];
if (n.key <= lo || n.key >= hi) throw std::runtime_error("BST order");
if (n.red && (t[n.left].red || t[n.right].red)) throw std::runtime_error("property 4");
int bl = black_height(n.left, lo, n.key) + !t[n.left].red;
int br = black_height(n.right, n.key, hi) + !t[n.right].red;
if (bl != br) throw std::runtime_error("property 5");
return bl;
}
int check() const {
if (t[root].red) throw std::runtime_error("property 2");
return black_height(root, -1000000, 1000000);
}
};
int main() {
RB good;
good.root = good.add(26, false,
good.add(17, true, good.add(14, false, good.add(10, true)), good.add(21, false)),
good.add(41, false, good.add(30, true), good.add(47, true)));
RB uneven;
uneven.root = uneven.add(26, false, uneven.add(17, false), uneven.add(41, false, uneven.add(30, false)));
for (const RB* tree : {&good, &uneven}) {
try { std::printf("valid, black-height %d\n", tree->check()); }
catch (const std::exception& e) { std::printf("invalid: %s\n", e.what()); }
}
}valid, black-height 2
invalid: property 5
The height bound
Lemma. The subtree rooted at any node contains at least internal nodes.
Proof. By induction on the height of . If the height is 0, is a NIL leaf, , and the subtree has internal nodes. Otherwise is internal with two children. A child has black-height if is red and if is black, so at least either way. The children have smaller height, so by induction each subtree has at least internal nodes, and the subtree of at least
Theorem. A red-black tree with internal nodes has height at most .
Proof. Let be the height and take a longest path from the root to a leaf, with edges. By property 4, no two red nodes are adjacent on it, and the leaf at its end is black, so at least half of the nodes below the root on the path are black: . By the lemma, . So , that is .
The intuition: property 5 makes the tree perfectly balanced if you only count black nodes, and property 4 lets the red nodes at most double the length of a path. Every query of the previous section (search, minimum, maximum, successor, predecessor) therefore runs in time on a red-black tree, with no change to its code.
How tight is the bound?
The program computes, for each height , the fewest internal nodes a red-black tree of height can have, by dynamic programming over (height, black-height, root colour) of subtrees. It is the tallest possible tree for its size, so it shows how close the worst case comes to .
import math
INF = float("inf")
# fewest internal nodes of a subtree with a given (levels, black-height, root colour);
# a NIL leaf has 0 levels, black-height 0, colour black and no internal nodes
best = {(0, 0, "B"): 0}
for levels in range(1, 17):
found = {}
states = list(best.items())
for (h1, b1, c1), n1 in states:
for (h2, b2, c2), n2 in states:
if max(h1, h2) != levels - 1 or b1 + (c1 == "B") != b2 + (c2 == "B"):
continue # wrong height, or property 5 fails
for c in "RB":
if c == "R" and "R" in (c1, c2):
continue # property 4
key = (levels, b1 + (c1 == "B"), c)
found[key] = min(found.get(key, INF), n1 + n2 + 1)
best.update(found)
print(f"{'height h':>8} {'fewest nodes n':>15} {'2 lg(n + 1)':>12}")
for h in range(0, 16, 3):
n = min(v for (lv, b, c), v in best.items() if lv == h + 1 and c == "B")
print(f"{h:>8} {n:>15} {2 * math.log2(n + 1):>12.2f}")height h fewest nodes n 2 lg(n + 1)
0 1 2.00
3 6 5.61
6 22 9.05
9 62 11.95
12 190 15.15
15 510 17.99
The tallest trees have height about : the factor 2 in the theorem is real. Such a tree has one path that alternates black and red as long as possible, while the rest of the tree is as small as property 5 allows. Randomly built red-black trees are much better than the worst case, close to , as Red-Black Insertion measures.
Note: The properties say nothing about how to restore them after a change. Inserting a node red keeps property 5 but may break property 4; deleting a black node breaks property 5. The next three lessons repair them with recolourings and rotations, in time.
Test yourself
What is the maximum height of a red-black tree with internal nodes?
- 10
- 20
- 1023
Which property is violated by a red root?
- property 2 (the root is black)
- property 4
- property 5
- none: a red root is allowed
In the proof of the height bound, why is ?
- Because every node is black
- Because property 4 forbids two red nodes in a row, so at least half the nodes below the root on a longest path are black
- Because of property 5 alone
- Because the tree is perfectly balanced
A subtree has black-height 4. At least how many internal nodes does it contain?
- 4
- 8
- 15
- 16