Sub topic 9
Red-black insertion: recolor or rotate
This chapter assumes you know the five red-black properties, how rotations work, and how a plain BST insert works. Insertion keeps the tree valid with a short repair loop called the fixup.
Insert red, then repair
Insert the new key as in an ordinary BST and color the new node red. This choice is deliberate. A red node adds no black node to any path, so the black-height property (equal black counts on every path) cannot break.
Only two properties can fail:
- The root is red. Recolor it black at the end.
- A red node has a red parent. This is the real work.
The fixup runs only while the new node z has a red parent. That parent is red, so it is not the root. The grandparent therefore exists and is black. The color of the uncle (the parent's sibling) decides the action.
| Uncle | Shape of z, parent, grandparent | Action |
|---|---|---|
| Red | Any | Recolor, then continue upward from the grandparent |
| Black | Triangle (z is an inner child) | Rotate the parent to make a line, then handle as a line |
| Black | Line (z is an outer child) | Rotate the grandparent, swap the colors of parent and grandparent, stop |
Why each case works
Red uncle. Making the parent and uncle black and the grandparent red keeps every path's black count unchanged. The grandparent may now have a red parent, so the loop repeats two levels higher. This case does no rotations, and it is why red-black trees do little structural work.
Black uncle. Recoloring cannot fix this case, because the black count would change on one side. A rotation moves a black node into the problem area. After one or two rotations the subtree root is black with two red children, and no red-red pair remains. The loop ends. This is the reason insertion does at most two rotations in total.
Implementation
RED, BLACK = "R", "B"
class Node:
def __init__(self, key, parent=None):
self.key, self.color = key, RED
self.left = self.right = None
self.parent = parent
class RBTree:
def __init__(self):
self.root = None
def _rotate(self, x, left):
y = x.right if left else x.left
if left:
x.right = y.left
if y.left: y.left.parent = x
y.left = x
else:
x.left = y.right
if y.right: y.right.parent = x
y.right = x
y.parent = x.parent
if x.parent is None: self.root = y
elif x is x.parent.left: x.parent.left = y
else: x.parent.right = y
x.parent = y
def insert(self, key):
parent, cur = None, self.root
while cur:
parent = cur
if key == cur.key: return
cur = cur.left if key < cur.key else cur.right
z = Node(key, parent)
if parent is None: self.root = z
elif key < parent.key: parent.left = z
else: parent.right = z
self._fixup(z)
def _fixup(self, z):
while z.parent and z.parent.color == RED:
p = z.parent
g = p.parent
left_side = p is g.left
u = g.right if left_side else g.left
if u and u.color == RED: # case 1: recolor
p.color = u.color = BLACK
g.color = RED
z = g
continue
if z is (p.right if left_side else p.left): # triangle
z = p
self._rotate(z, left_side)
p = z.parent
p.color, g.color = BLACK, RED # line
self._rotate(g, not left_side)
self.root.color = BLACK
def preorder(n):
if n:
yield f"{n.key}{n.color}"
yield from preorder(n.left)
yield from preorder(n.right)
t = RBTree()
for k in range(1, 8):
t.insert(k)
print(" ".join(preorder(t.root))) # 2B 1B 4R 3B 6B 5R 7RSorted input would turn a plain BST into a list. Here the tree stays shallow, with root 2 and longest path 2, 4, 6, 5.
Cost
The loop moves up one grandparent per iteration, so recoloring takes O(log n) steps in the worst case. Rotations happen at most twice per insert. Together with the O(log n) descent, insertion is O(log n).
Exercise
Insert 10, 5, 15, 3 into an empty red-black tree, then insert 1. Which case applies for 1, and what is the final color of 5?
Show answer
After 10, 5, 15 the tree is 10 black with red children 5 and 15. Inserting 3 gives a red parent (5) and a red uncle (15). Recolor 5 and 15 black and 10 red, then make the root black again. Inserting 1 goes under 3, which is red, and the uncle (the right child of 5) is None, so black. 1 is an outer child of 3, so this is the line case. Rotate right at 5 and swap colors. 3 becomes black and 5 becomes red, so the final color of 5 is red.