Sub topic 10
Red-Black Deletion and the Double-Black Problem
This chapter assumes you know the five red-black properties, left and right rotations, and the insertion fixup that looks at the uncle's color. It covers deletion, which is the hardest red-black operation. Deletion can break the equal-black-count rule in a way insertion never does.
Why deletion is harder than insertion
The five properties are:
- Every node is red or black.
- The root is black.
- Every nil leaf counts as black.
- A red node has only black children.
- Every path from a node down to a nil leaf passes through the same number of black nodes.
Insertion adds a red node. That can break property 4 (red parent, red child), which a local recoloring or a rotation repairs. Deletion has no such cheap case. If you remove a black node, every path through that position loses one black node, so property 5 fails for the whole subtree.
If you remove a red node, nothing breaks. No path changes its black count, and no red-red pair appears, because the removed node's children must be black.
So the work reduces to one question: which node was physically removed, and what color was it?
Which node is physically removed
Deletion starts like a plain BST delete. Let z be the node holding the key.
- If
zhas at most one child,zis unlinked and its child (possibly nil) takes its place. The removed color isz's color. - If
zhas two children, findy, the in-order successor (the leftmost node in the right subtree). Unlinky, putyinz's position, and giveythe color ofz. The removed color isy's original color.
Call the node that moves into the vacated position x. It may be nil.
- If the removed color is red, you are done.
- If it is black,
xcarries an extra black. Ifxis red, recolor it black and you are done, because the extra black is absorbed. Ifxis black or nil, it is doubly black, and the fixup loop begins.
A doubly black node is not a real color. It is bookkeeping for the fact that paths through x are one black node short.
The four cases
Let p be the parent of x, and let w be the sibling of x. Because x's side is one black short, w is never nil. The nephews are the children of w. The near nephew is on the same side as x, and the far nephew is on the opposite side. The cases below assume x is a left child. When x is a right child, swap left and right throughout.
| Case | Sibling `w` | Nephews | Action | Result |
|---|---|---|---|---|
| 1 | Red | Both black (forced) | Color `w` black and `p` red, rotate left at `p` | New sibling is black, so go to case 2, 3 or 4 |
| 2 | Black | Both black | Color `w` red, move the extra black up to `p` | Loop continues at `p`, or stops if `p` is red |
| 3 | Black | Near red, far black | Color near nephew black and `w` red, rotate right at `w` | Now case 4 |
| 4 | Black | Far red | `w` takes `p`'s color, `p` and far nephew become black, rotate left at `p` | Extra black disposed of, done |
Why each case works:
- Case 1 does not repair anything. It changes the sibling from red to black without changing any black counts, so that cases 2 to 4 apply. After the rotation,
xhas the same parentp, now red, and a black sibling. - Case 2 is the only case that loops. Making
wred removes one black from the sibling side, which equalizes the two sides ofp. The deficit is now atp. Ifpis red, recoloring it black pays the debt. - Case 3 is a preparation step, like the left-right case in AVL trees. It moves the red nephew to the far side.
- Case 4 rotates
pdown tox's side.pis colored black, sox's paths gain one black node. The far nephew is recolored black, so the paths on the other side keep their count.
Cases 1, 3 and 4 each end in at most a constant number of rotations. Case 2 can repeat up to the root, but it only recolors. Deletion therefore does O(log n) recoloring and at most three rotations. That is the main practical advantage over AVL deletion, which may rotate at every level on the way up.
A complete implementation
The code below uses parent pointers and follows the usual textbook structure. It keeps nil as None, so the fixup receives x and its parent separately. A nil x has no .parent attribute to read.
RED, BLACK = "R", "B"
class Node:
def __init__(self, key, color, left=None, right=None):
self.key, self.color = key, color
self.left, self.right, self.parent = left, right, None
for c in (left, right):
if c:
c.parent = self
def color(n):
return BLACK if n is None else n.color
def rotate_left(root, x):
y = x.right
x.right = y.left
if y.left:
y.left.parent = x
y.parent = x.parent
if x.parent is None:
root = y
elif x is x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.left = x
x.parent = y
return root
def rotate_right(root, x):
y = x.left
x.left = y.right
if y.right:
y.right.parent = x
y.parent = x.parent
if x.parent is None:
root = y
elif x is x.parent.right:
x.parent.right = y
else:
x.parent.left = y
y.right = x
x.parent = y
return root
def transplant(root, u, v):
if u.parent is None:
root = v
elif u is u.parent.left:
u.parent.left = v
else:
u.parent.right = v
if v:
v.parent = u.parent
return root
def fixup(root, x, parent):
while x is not root and color(x) == BLACK:
if x is parent.left:
w = parent.right
if color(w) == RED: # case 1
w.color, parent.color = BLACK, RED
root = rotate_left(root, parent)
w = parent.right
if color(w.left) == BLACK and color(w.right) == BLACK:
w.color = RED # case 2
x, parent = parent, parent.parent
else:
if color(w.right) == BLACK: # case 3
w.left.color, w.color = BLACK, RED
root = rotate_right(root, w)
w = parent.right
w.color, parent.color = parent.color, BLACK # case 4
w.right.color = BLACK
root = rotate_left(root, parent)
x = root
else: # mirror image
w = parent.left
if color(w) == RED:
w.color, parent.color = BLACK, RED
root = rotate_right(root, parent)
w = parent.left
if color(w.left) == BLACK and color(w.right) == BLACK:
w.color = RED
x, parent = parent, parent.parent
else:
if color(w.left) == BLACK:
w.right.color, w.color = BLACK, RED
root = rotate_left(root, w)
w = parent.left
w.color, parent.color = parent.color, BLACK
w.left.color = BLACK
root = rotate_right(root, parent)
x = root
if x:
x.color = BLACK
return root
def delete(root, key):
z = root
while z and z.key != key:
z = z.left if key < z.key else z.right
if z is None:
return root
removed = z.color
if z.left is None:
x, parent = z.right, z.parent
root = transplant(root, z, z.right)
elif z.right is None:
x, parent = z.left, z.parent
root = transplant(root, z, z.left)
else:
y = z.right
while y.left:
y = y.left
removed = y.color
x = y.right
if y.parent is z:
parent = y
else:
parent = y.parent
root = transplant(root, y, y.right)
y.right = z.right
y.right.parent = y
root = transplant(root, z, y)
y.left = z.left
y.left.parent = y
y.color = z.color
if removed == BLACK:
root = fixup(root, x, parent)
return root
def check(root):
"""Return the black-height, or raise ValueError if a property fails."""
if color(root) != BLACK:
raise ValueError("root must be black")
def walk(n):
if n is None:
return 1
if n.color == RED and (color(n.left) == RED or color(n.right) == RED):
raise ValueError("red node %r has a red child" % n.key)
lh, rh = walk(n.left), walk(n.right)
if lh != rh:
raise ValueError("black-height mismatch at %r" % n.key)
return lh + (1 if n.color == BLACK else 0)
return walk(root)
def inorder(n):
return inorder(n.left) + [n.key] + inorder(n.right) if n else []
def build(keys, depth, last):
if not keys:
return None
mid = len(keys) // 2
c = RED if depth == last else BLACK
return Node(keys[mid], c,
build(keys[:mid], depth + 1, last),
build(keys[mid + 1:], depth + 1, last))
keys = list(range(1, 11))
root = build(keys, 0, len(keys).bit_length() - 1)
print(check(root)) # 4
for k in [6, 1, 9, 3, 10, 2, 7, 5, 8, 4]:
root = delete(root, k)
check(root) # raises if any property breaks
print(inorder(root)) # []The build helper makes a valid starting tree. It splits the keys at the midpoint, which fills every level except the last, and colors the last level red. The loop deletes all ten keys in a scrambled order and runs the validator after each step. This exercises the fixup cases without needing an insertion routine.
Common mistakes
- Dropping the parent of a nil
x. If you writex.parentwhenxis nil, you get an error. Trackparentseparately, as above. Libraries that use a shared sentinel nil node avoid this by writing the parent into the sentinel, which is a trick that breaks easily. - Forgetting the final
x.color = BLACK. This line handles the case wherexis a red node that absorbs the extra black, and it also keeps the root black. - Reading the removed color from the wrong node. With two children, the color that matters is the successor's original color, saved before
y.color = z.coloroverwrites it. - Mixing up near and far nephew. Case 4 tests the far nephew first. If you test the near nephew first, you apply case 3 when a single rotation would do.
Summary of costs
| Operation | Rotations (worst case) | Recolorings (worst case) |
|---|---|---|
| Red-black insert | 2 | O(log n) |
| Red-black delete | 3 | O(log n) |
| AVL insert | 2 (one single or double rotation) | none |
| AVL delete | O(log n) | none |
Every operation is still O(log n) in total, since finding the node already costs that much. The difference is how much structural change follows. A workload with many deletions benefits from the bounded rotation count.
Exercise
A black node with no children, whose sibling is black with two nil children, is deleted. Its parent is red. Which case applies, and does the fixup loop continue?
Show answer
Case 2 applies. The sibling becomes red and the extra black moves up to the parent. Because the parent is red, the loop ends and the parent is recolored black, which restores equal black counts on both sides. No rotation is needed.
Exercise
Why must the sibling w of a doubly black node never be nil?
Show answer
Before deletion every path from the parent through x's side had the same black count as the paths through w. x's side lost a black node, but it had at least one before, so w's side has at least one black node, and a nil leaf contributes none beyond the baseline. A nil sibling would mean that side has black-height 1 while x's side originally had at least 2, which contradicts property 5.
Exercise
In case 1 the sibling is red. Why can the fixup not stop after that step?
Show answer
The rotation and the color swap leave all black counts unchanged, so x is still doubly black. Their only effect is to give x a black sibling, so that case 2, 3 or 4 can apply.