Sub topic 9
Red-Black Insertion: Recolor or Rotate
This chapter assumes you know binary search tree insertion, the left and right rotations from the earlier chapter, and the five red-black properties. You should also be comfortable reading Python classes that use parent pointers.
The strategy: insert red, then repair
A red-black tree insertion has two phases. First, insert the key exactly as in a plain BST. Second, walk back up and repair any violated property.
The new node is always colored red. The reason comes from the properties:
- Property 5 says every path from a node to its nil leaves has the same number of black nodes. A black insertion adds one black node to one path and breaks this for the whole tree.
- A red insertion leaves every black count unchanged.
- A red insertion can only break one of two other rules. If the tree was empty, the new red node is the root, which violates "the root is black". Otherwise, if its parent is red, it violates "a red node has no red child".
So the repair has only two jobs: fix the root color and remove a red-red conflict. Call the new node z, its parent p, its grandparent g, and its uncle u, which is p's sibling.
If p is red, then p is not the root, because the root is black. So g exists. Also, g must be black, because a red g with a red child p would already have broken the rules before the insertion. These two facts hold throughout the repair.
The three cases
Everything depends on the uncle's color. A missing uncle (None) counts as black, since nil leaves are black.
| Case | Uncle | Shape of z, p, g | Action |
|---|---|---|---|
| 1 | Red | Any | Recolor `p` and `u` black, `g` red. Continue the repair from `g`. |
| 2 | Black | Inner (a "triangle": `z` is a right child of a left child, or the mirror) | Rotate `p` toward the outside. This turns the shape into case 3. |
| 3 | Black | Outer (a "line": left-left or right-right) | Recolor `p` black and `g` red, then rotate `g` the opposite way. Done. |
Case 1: red uncle, recolor
Both p and u are red, and g is black. Push the blackness down: make p and u black and g red.
Every root-to-leaf path through g crosses exactly one of p or u, and it crosses g once. Before, a path counted g as black. After, it counts p or u as black instead. Black counts do not change.
The red-red conflict between z and p is gone. But g is now red, and its own parent might be red, so the problem may have moved up two levels. The loop continues with z = g. If g reaches the root, it gets recolored black at the end. That is the only step that raises the black-height of the whole tree.
Case 2: black uncle, inner child
Suppose p is the left child of g and z is the right child of p. Recoloring alone cannot fix this, because the black count on the uncle's side is already one lower than on the p side. A rotation is needed.
A single rotation at g would leave z in the wrong place, so first rotate left at p. Now p is the left child of z, and z is the left child of g. The shape is a left-left line, which is case 3, with the roles of z and p swapped. Only the labels change. Set z = p and carry on.
Case 3: black uncle, outer child
Suppose p is the left child of g and z is the left child of p. Color p black and g red, then rotate right at g. The subtree root changes from g to p:
- The old
gis now a red child of the new black root, with the old uncle subtree beneath it. zstays as the red child on the other side.- The subtree root is black. Before the repair, its root
gwas black, so the black count on every path is unchanged. - The new subtree root is black, so no red-red conflict can reach above it. The loop ends.
The rotation preserves BST order for the same reason as in AVL trees. It only reattaches subtrees whose key ranges stay on the correct sides.
Implementation
This version uses parent pointers, because the repair needs to find the grandparent and uncle. Rotations must keep parent links and the tree's root up to date.
RED, BLACK = "R", "B"
class Node:
def __init__(self, key):
self.key = key
self.color = RED # new nodes start red
self.left = None
self.right = None
self.parent = None
class RBTree:
def __init__(self):
self.root = None
def _replace_child(self, parent, old, new):
if parent is None:
self.root = new
elif parent.left is old:
parent.left = new
else:
parent.right = new
def _rotate_left(self, x):
y = x.right
x.right = y.left
if y.left:
y.left.parent = x
y.parent = x.parent
self._replace_child(x.parent, x, y)
y.left = x
x.parent = y
def _rotate_right(self, y):
x = y.left
y.left = x.right
if x.right:
x.right.parent = y
x.parent = y.parent
self._replace_child(y.parent, y, x)
x.right = y
y.parent = x
def insert(self, key):
parent, cur = None, self.root
while cur:
parent = cur
if key == cur.key:
return # ignore duplicates
cur = cur.left if key < cur.key else cur.right
z = Node(key)
z.parent = parent
if parent is None:
self.root = z
elif key < parent.key:
parent.left = z
else:
parent.right = z
self._fix_insert(z)
def _fix_insert(self, z):
while z.parent is not None and z.parent.color == RED:
p = z.parent
g = p.parent # exists: a red parent is never the root
if p is g.left:
u = g.right
if u is not None and u.color == RED: # case 1
p.color = u.color = BLACK
g.color = RED
z = g
continue
if z is p.right: # case 2
z = p
self._rotate_left(z)
p = z.parent
p.color = BLACK # case 3
g.color = RED
self._rotate_right(g)
else:
u = g.left
if u is not None and u.color == RED: # case 1
p.color = u.color = BLACK
g.color = RED
z = g
continue
if z is p.left: # case 2
z = p
self._rotate_right(z)
p = z.parent
p.color = BLACK # case 3
g.color = RED
self._rotate_left(g)
self.root.color = BLACK
def height(n):
return 0 if n is None else 1 + max(height(n.left), height(n.right))
def black_height(n):
"""Return the black-height, raising AssertionError on a violation."""
if n is None:
return 1
if n.color == RED:
for c in (n.left, n.right):
assert c is None or c.color == BLACK, "red node with red child"
lh, rh = black_height(n.left), black_height(n.right)
assert lh == rh, "black-height mismatch"
return lh + (1 if n.color == BLACK else 0)
tree = RBTree()
for k in range(1, 8):
tree.insert(k)
assert tree.root.color == BLACK
print(tree.root.key, height(tree.root), black_height(tree.root)) # 2 4 3Two details matter in the code:
- In case 2,
pis reassigned after the rotation. After_rotate_left(z), the oldzis the parent of the oldp, soz.parentis the node that must be colored black. - Case 1 uses
continue, so it re-tests the loop condition with the newz. Cases 2 and 3 fall through to the end of the loop body. After case 3,z.parentis black, so the loop exits on its own.
Worked trace: inserting 1 through 7 in order
Sorted input is the worst case for a plain BST. Here is what the repairs do. Nodes are written as key and color, with children in parentheses.
| Insert | Situation | Action | Resulting tree |
|---|---|---|---|
| 1 | Empty tree | Root recolored black | 1B |
| 2 | Parent black | None | 1B(-, 2R) |
| 3 | Parent 2 red, uncle none, outer | Case 3: rotate left at 1 | 2B(1R, 3R) |
| 4 | Parent 3 red, uncle 1 red | Case 1: recolor, root stays black | 2B(1B, 3B(-, 4R)) |
| 5 | Parent 4 red, uncle none, outer | Case 3: rotate left at 3 | 2B(1B, 4B(3R, 5R)) |
| 6 | Parent 5 red, uncle 3 red | Case 1: 4 turns red, its parent 2 is black | 2B(1B, 4R(3B, 5B(-, 6R))) |
| 7 | Parent 6 red, uncle none, outer | Case 3: rotate left at 5 | 2B(1B, 4R(3B, 6B(5R, 7R))) |
The final tree has height 4. An AVL tree built from the same input has height 3, because it keeps heights tighter. Red-black trees accept a looser shape in exchange for cheaper repairs.
Cost
An insertion walks down once and then repairs on the way up:
- Case 1 can repeat, moving up two levels each time, so recoloring costs O(log n) in the worst case.
- Cases 2 and 3 end the loop. A single insertion therefore performs at most two rotations, whatever the tree's size.
- Total time is O(log n), because the red-black height bound guarantees that logarithmic path length.
Only case 1 can propagate, and it only changes colors. Rotations touch a constant number of pointers, which matters in systems where restructuring is expensive.
Common errors
- Treating a missing uncle as red.
Noneis a black leaf. The test must beu is not None and u.color == RED. - Skipping the final root recoloring. Case 1 can turn the root red. Always set
root.color = BLACKafter the loop. - Rotating
gin case 2. Ifzis an inner child, a rotation atgdoes not remove the conflict. Rotate atpfirst. - Forgetting the mirror cases. The
elsebranch must mirror every direction, including which rotation is used. - Using stale variables after a rotation. In case 2, recompute
pfrom the newz. - Not updating
root. A rotation at the top of the tree changes the root. The_replace_childhelper handles it.
Exercise
Starting from an empty red-black tree, insert 10, 20, 30, and then 15. Which case applies for each of the last two insertions, and what are the final colors?
Show answer
Inserting 10 makes it the root, recolored black. Inserting 20 gives a red right child, and the parent is black, so nothing happens. Inserting 30 has a red parent (20) and no uncle, which counts as black. This is an outer right-right shape, so case 3 applies: 20 turns black, 10's parent link changes through a left rotation at 10, and 10 turns red. The tree is 20B(10R, 30R). Inserting 15 makes it the right child of 10. Its parent 10 is red and its uncle 30 is red, so case 1 applies: 10 and 30 become black and 20 becomes red. Since 20 is the root, it is recolored black. The final tree is 20B(10B(-, 15R), 30B).
Exercise
Why can the red-black insertion loop run for O(log n) iterations but perform at most two rotations?
Show answer
Only case 1 repeats, and it only recolors nodes while moving the problem two levels up. Cases 2 and 3 perform the rotations and always end the loop, because case 3 leaves a black subtree root that cannot conflict with anything above it. Case 2 always flows into case 3, so the total is at most two rotations per insertion.