Sub topic 8
Red-black trees: the color rules
This chapter assumes you can read Python and know binary search tree (BST) search and insertion. It also assumes you know the rotations from earlier in this tutorial, and that you are comfortable with root, leaf, subtree and height. It covers the rules a red-black tree must satisfy, how to check them by hand and in code, and what they imply about the tree's shape. The repair procedures for insertion and deletion come in later chapters.
The idea: balance stored in one bit
An AVL tree keeps balance by tracking subtree heights and keeping them within one of each other. A red-black tree uses a looser rule. Every node carries one extra bit, its color, which is red or black. A small set of rules about those colors guarantees that no root-to-leaf path is more than about twice as long as any other.
The colors are only bookkeeping. They have no meaning for the data. Insertion and deletion are allowed to break the rules temporarily, then run a fixup that recolors nodes and rotates until the rules hold again.
The five properties
A binary search tree is a red-black tree if it satisfies all five of these properties.
- Every node is either red or black.
- The root is black.
- Every leaf is black. Here "leaf" means the empty (nil) child pointer, not a node holding a key.
- A red node has no red child. Both children of a red node are black.
- For every node, all paths from that node down to a nil leaf contain the same number of black nodes.
The number in property 5 is the node's black-height. By convention it does not count the node itself, but it counts the nil leaf. Implementations differ on this, so decide on a convention and apply it everywhere.
Two consequences follow directly:
- A red node never has a red parent. Since the root is black, a red node is never the root.
- If a red node has one nil child and one real child, the real child must be a black node with black-height 1 or more. The nil side would then have a lower count, which breaks property 5. So a red node has either two real black children or two nil children.
Reading a colored tree
Here is a valid red-black tree. Red nodes are drawn in red and black nodes in dark gray.
To check property 5, count black nodes along each path, including the root:
| Path to a nil leaf | Black nodes on the path |
|---|---|
| 10, 5, 3 | 10, 3 = 2 |
| 10, 5, 7 | 10, 7 = 2 |
| 10, 15, 12 | 10, 15 = 2 |
| 10, 15, 20 | 10, 15 = 2 |
All paths agree, so the black-height is 2, or 3 if you count the nil leaf. The red nodes 5, 12 and 20 each have only black children, so property 4 holds. The root is black, so property 2 holds.
Colors do not have to alternate by level. A black node can have black children. Adding black nodes is how a tree absorbs extra depth on one side, as long as the other side gets matching black nodes.
Why the rules force a balanced shape
Properties 4 and 5 together constrain how uneven a tree can get.
- The shortest possible path from a node to a leaf is all black nodes.
- The longest possible path alternates black and red, because property 4 forbids two reds in a row.
- Property 5 says both paths contain the same number of black nodes, so the longest path has at most twice as many nodes as the shortest.
That is the whole intuition for the height guarantee. A later chapter turns it into a proof that the height is at most 2·log₂(n + 1). Unlike AVL, a red-black tree can have one side that is noticeably deeper than the other. It cannot be arbitrarily deeper.
Writing the check in code
The properties are mechanical, which makes them easy to test. The validator below walks the tree once, passing down the allowed key range to check BST ordering, and returns the black-height up the recursion. It raises ValueError when a rule fails. Nil children return 1, which is the convention that counts the nil leaf as a black node.
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)
def try_check(label, tree):
try:
print(label, "ok, black-height", check_rb(tree))
except ValueError as e:
print(label, "FAIL:", e)
# The tree from the diagram.
good = RBNode(
10, BLACK,
RBNode(5, RED, RBNode(3, BLACK), RBNode(7, BLACK)),
RBNode(15, BLACK, RBNode(12, RED), RBNode(20, RED)),
)
try_check("diagram tree:", good) # ok, black-height 3
try_check("red root:", RBNode(1, RED)) # FAIL: root must be black
try_check("red-red:", RBNode(2, BLACK, RBNode(1, RED, RBNode(0, RED)), None))
# FAIL: red node 1 has a red child
try_check("uneven:", RBNode(2, BLACK, RBNode(1, BLACK), None)) # FAIL: black-height mismatch at 2
try_check("bad order:", RBNode(2, BLACK, RBNode(5, RED), None)) # FAIL: BST order violated at 5The check order matters for error messages. The ordering and red-red checks run before recursion, so they report the nearest offending node. The black-height comparison runs after both subtrees return, so a mismatch is reported at the lowest node where the two sides disagree.
Property 1 (every node is red or black) is enforced by how RBNode is used, since a node holds one color value. If you want to defend against typos, add a check that n.color in (RED, BLACK).
Common mistakes
- Forgetting that nil leaves count as black. Without this, a red node with one child looks legal. It is not: the nil side has one fewer black node than the real child's side.
- Counting black-height inconsistently. Some texts include the starting node and some exclude it. Pick one convention and use it for every comparison. The validator above counts the node itself and the nil leaf, so a lone black node has black-height 2 and a nil has 1.
- Believing colors alternate. Only red nodes are restricted. Two black nodes in a row are fine.
- Treating the root rule as essential to balance. A red root would not break the height argument. Property 2 exists to simplify the fixup code, because recoloring a root black never violates any other property.
- Testing only the colors. A tree can satisfy every color rule and still be a broken BST after a bad rotation. Check ordering and colors together, as
check_rbdoes.
How this compares to AVL so far
| Row | AVL | Red-black |
|---|---|---|
| Per-node data | Height or balance factor | One color bit |
| Balance rule | Child heights differ by at most 1 | No red-red, equal black count on every path |
| Longest path vs. shortest | Closer to equal | Up to 2 times |
| Rule is checked by | Comparing two heights | Counting black nodes along paths |
The looser rule is the reason red-black trees usually do less rebalancing work per update. The cost is a taller tree in the worst case. A later chapter weighs those effects against specific workloads.
Practice
Exercise
A tree has a black root 8 with a red left child 4 and a black right child 12. Node 4 has one real child, a black node 2. Nodes 2 and 12 have no children. Is this a valid red-black tree? If not, which property fails and why?
Show answer
It is not valid. Property 5 fails. Count black nodes on the path 8, 4, 2, nil on the left: 8 and 2, plus the nil leaf. Now take the path 8, 4, nil through 4's missing right child: only 8 and the nil leaf. These two paths from node 4 differ, because node 4's left side has black-height 2 (node 2 and the nil) and its right side has black-height 1 (just the nil). The check_rb function would report a black-height mismatch at 4.
Exercise
Why must the longest root-to-leaf path in a red-black tree be at most twice as long as the shortest one?
Show answer
Every path has the same number of black nodes (property 5). The shortest path can be all black. The longest path can add red nodes, but property 4 forbids two red nodes in a row, so there is at most one red node per black node. The longest path therefore has at most twice as many nodes as the shortest.