Sub topic 8
Red-black trees: the color rules
This chapter assumes you can read Python, know how a binary search tree (BST) orders keys, and have seen rotations and AVL balance factors. Here we cover the rules that define a red-black tree. Insertion and deletion repairs come in later chapters.
The idea
An AVL tree stores a height at each node and keeps sibling subtrees within one level of each other. A red-black tree stores one bit per node, a color, and keeps the tree roughly balanced with a looser rule. The tree can be up to twice as tall as a perfectly balanced one, but fixing it after an update needs fewer rotations.
The five properties
A binary search tree is a red-black tree if it satisfies these rules:
- Every node is red or black.
- The root is black.
- Every empty child (a nil leaf) counts as black.
- A red node has no red child. Equivalently, no two reds are adjacent on any path.
- Every path from a node down to its nil leaves contains the same number of black nodes.
The number in rule 5 is the black-height of the node. It counts black nodes on the way down, and by convention the nil leaf is included in the count, as the code below does.
Why the rules force balance
Rule 5 says all root-to-leaf paths have the same number of black nodes. Rule 4 says reds can only be spaced out between blacks, never stacked. So the longest possible path alternates black and red, while the shortest has only blacks. The longest path is therefore at most twice the shortest. The height bound chapter makes this precise.
In this tree every path from the root to a nil leaf has black-height 2: the black root and the black nil leaf. The red nodes add length without changing the black count.
Checking the rules in code
The function below checks properties 2, 4 and 5, plus BST ordering. Missing children are returned as black-height 1, which implements rule 3.
RED, BLACK = "R", "B"
class RBNode:
def __init__(self, key, color, left=None, right=None):
self.key = key
self.color = color
self.left = left
self.right = right
def check_rb(root):
"""Raise ValueError if a red-black property fails; return the black-height."""
if root is not None and root.color != BLACK:
raise ValueError("root must be black")
def walk(n, lo, hi):
if n is None:
return 1 # empty (nil) leaves count as black
if (lo is not None and n.key <= lo) or (hi is not None and n.key >= hi):
raise ValueError("BST order violated at %r" % n.key)
if n.color == RED:
for c in (n.left, n.right):
if c is not None and c.color == RED:
raise ValueError("red node %r has a red child" % n.key)
lh = walk(n.left, lo, n.key)
rh = walk(n.right, n.key, hi)
if lh != rh:
raise ValueError("black-height mismatch at %r" % n.key)
return lh + (1 if n.color == BLACK else 0)
return walk(root, None, None)
tree = RBNode(2, BLACK, RBNode(1, RED), RBNode(3, RED))
print(check_rb(tree)) # 2The walk function returns the black-height of each subtree and compares the left and right values. A mismatch means rule 5 is broken somewhere below that node.
Common mistakes
- Checking only that no two reds touch, and forgetting rule 5. A tree of one long black chain with no reds passes rule 4 but is not balanced, and it fails rule 5 only when some path is shorter.
- Counting red nodes in the black-height. Only black nodes count.
- Forgetting the black root. After a recolor during insertion, the root can turn red, so implementations set it black at the end.
- Treating a one-child black node as fine. A black node with exactly one child must have a red leaf child, because otherwise the two sides have different black-heights.
Comparing with AVL
| Aspect | AVL tree | Red-black tree |
|---|---|---|
| Stored per node | Height or balance factor | One color bit |
| Balance rule | Child heights differ by at most 1 | Equal black count, no red-red |
| Height | About 1.44 log n at worst | At most 2 log n at worst |
| Lookup | Slightly faster, tree is shallower | Slightly slower |
Exercise
A tree has a black root with a single child, and that child is a black leaf with no children of its own. Does it satisfy the red-black properties? Explain using black-heights.
Show answer
No. The root's left side has a nil leaf directly, with black-height 1, while its right side goes through a black child and then a nil leaf, with black-height 2. Rule 5 fails because the two paths have different black counts. Making the child red fixes it, since a red node adds no black count and has no red child.
Exercise
Which of the five properties can a plain BST insertion of a new red leaf break, and which cannot?
Show answer
It can break rule 4 if the parent is red, and rule 2 if the tree was empty so the new root is red. It cannot break rule 5, because a red node adds no black nodes to any path.