Red-Black Deletion
Deletion is the harder half of red-black trees, but it follows the same plan as insertion: do the plain BST operation, notice which property can fail, and repair it with a loop that moves the problem up the tree and ends with a few rotations. The plain operation is TREE-DELETE from Insertion and Deletion with Transplant, with two small changes to remember colours. The repair has four cases, and at most three rotations happen in total.
Which node really disappears
TREE-DELETE removes node from the tree, but in the two-children case the node that leaves its position is 's successor , which moves up into 's place. So track:
- : the node removed from the tree, or moved within it. If has at most one child, ; otherwise is 's successor, and takes over 's colour when it moves into 's place, so the colours at 's position do not change.
- 's original colour: the colour that has effectively vanished from 's old position.
- : the node that moves into 's old position (a child of , possibly the sentinel).
If was red, nothing breaks: no black counts change, and no two reds can meet (the node that replaces a red node has a black parent). If was black, every path that went through 's old position now has one black node too few. Think of as carrying an extra black: it counts twice. If is red, colour it black and everything is fixed. If is black ("doubly black"), the extra black must be pushed somewhere, and that is the fix-up.
RB-DELETE(T, z)
1 y = z, y_color = y.color
2 if z.left == T.nil
3 x = z.right, RB-TRANSPLANT(T, z, z.right)
4 elseif z.right == T.nil
5 x = z.left, RB-TRANSPLANT(T, z, z.left)
6 else y = TREE-MINIMUM(z.right), y_color = y.color
7 x = y.right
8 if y != z.right
9 RB-TRANSPLANT(T, y, y.right)
10 y.right = z.right, y.right.parent = y
11 else x.parent = y // also when x is T.nil
12 RB-TRANSPLANT(T, z, y)
13 y.left = z.left, y.left.parent = y, y.color = z.color
14 if y_color == BLACK
15 RB-DELETE-FIXUP(T, x)RB-TRANSPLANT is TRANSPLANT with the test if v != NIL removed: it sets v.parent even when is the sentinel. The fix-up needs x.parent to work when is the sentinel, and that is the one place where the sentinel's parent field is used.
The fix-up cases
While is doubly black and not the root, let be 's sibling. Assume is a left child; the other side is the mirror image. is an internal node: the paths through must contain as many black nodes as those through counting the extra black, so at least one.
- Case 1: is red. Then 's parent is black and 's children are black. Colour black and the parent red, rotate left at the parent. Black counts are unchanged, and now has a black sibling (one of 's old children): go on to case 2, 3 or 4.
- Case 2: is black with two black children. Take one black off both and : becomes red, and the extra black moves up to the parent. Set to the parent and continue. If the parent is red, the loop stops and the last line colours it black.
- Case 3: is black, its left child (the near nephew) is red and its right child black. Swap the colours of and its left child and rotate right at . The new sibling is black with a red right child: case 4.
- Case 4: is black and its right child (the far nephew) is red. Give the parent's colour, colour the parent and the far nephew black, and rotate left at the parent. The extra black is absorbed: the paths through gain a black node (the old parent, now black above ), and the paths through the old keep their counts. Set to the root to end the loop.
RB-DELETE-FIXUP(T, x)
1 while x != T.root and x.color == BLACK
2 if x == x.parent.left
3 w = x.parent.right
4 if w.color == RED // case 1
5 w.color = BLACK, x.parent.color = RED
6 LEFT-ROTATE(T, x.parent), w = x.parent.right
7 if w.left.color == BLACK and w.right.color == BLACK // case 2
8 w.color = RED, x = x.parent
9 else if w.right.color == BLACK // case 3
10 w.left.color = BLACK, w.color = RED
11 RIGHT-ROTATE(T, w), w = x.parent.right
12 w.color = x.parent.color // case 4
13 x.parent.color = BLACK, w.right.color = BLACK
14 LEFT-ROTATE(T, x.parent), x = T.root
15 else (the same with "left" and "right" exchanged)
16 x.color = BLACKCost and rotations. Only case 2 repeats, and each repetition moves one level up, so the loop runs times with work each; with the walk to the successor, deletion is . Cases 1, 3 and 4 rotate once each. Case 4 ends the loop; case 3 leads straight to case 4; case 1 leads to case 2 (which then ends at once, because the parent is now red), 3 or 4. So at most three rotations occur per deletion.
A trace
The program builds a tree from nine keys and deletes five of them, printing the fix-up steps and the tree after each deletion; the letter after each key is its colour. The first three deletions need no fix-up loop: 5 and 65 are red, and 90 is black but its replacement , the red 75, simply turns black. Deleting 10 runs case 3 and then case 4; deleting the root 70 (its successor 75 moves up) runs case 1 and then case 2, which stops at once because case 1 made the parent red.
RED, BLACK = "R", "B"
class Node:
__slots__ = ("key", "color", "left", "right", "parent")
def __init__(self, key, color, nil):
self.key, self.color, self.left, self.right, self.parent = key, color, nil, nil, nil
class RBTree:
def __init__(self):
self.nil = Node(None, BLACK, None)
self.root, self.say = self.nil, None
def rotate(self, x, d): # d == "left": x's right child moves up
nil, o = self.nil, ("right" if d == "left" else "left")
y = getattr(x, o)
setattr(x, o, getattr(y, d))
if getattr(y, d) is not nil: getattr(y, d).parent = x
y.parent = x.parent
if x.parent is nil: self.root = y
elif x is x.parent.left: x.parent.left = y
else: x.parent.right = y
setattr(y, d, x)
x.parent = y
def insert(self, key):
z, y, x = Node(key, RED, self.nil), self.nil, self.root
while x is not self.nil:
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is self.nil: self.root = z
elif key < y.key: y.left = z
else: y.right = z
while z.parent.color == RED:
p = z.parent; g = p.parent
a, b = ("left", "right") if p is g.left else ("right", "left")
u = getattr(g, b)
if u.color == RED:
p.color = u.color = BLACK; g.color = RED; z = g; continue
if z is getattr(p, b):
z = p; self.rotate(z, a); p = z.parent
p.color = BLACK; g.color = RED; self.rotate(g, b)
self.root.color = BLACK
def find(self, k):
x = self.root
while x is not self.nil and x.key != k:
x = x.left if k < x.key else x.right
return x
def transplant(self, u, v): # RB-TRANSPLANT: sets v.parent even for nil
if u.parent is self.nil: self.root = v
elif u is u.parent.left: u.parent.left = v
else: u.parent.right = v
v.parent = u.parent
def delete(self, z):
nil = self.nil
y, y_color = z, z.color
if z.left is nil:
x = z.right; self.transplant(z, z.right)
elif z.right is nil:
x = z.left; self.transplant(z, z.left)
else:
y = z.right
while y.left is not nil: y = y.left
y_color, x = y.color, y.right
if y is not z.right:
self.transplant(y, y.right)
y.right = z.right; y.right.parent = y
else:
x.parent = y
self.transplant(z, y)
y.left = z.left; y.left.parent = y; y.color = z.color
if y_color == BLACK:
self.fixup(x)
def fixup(self, x):
while x is not self.root and x.color == BLACK:
a, b = ("left", "right") if x is x.parent.left else ("right", "left")
w = getattr(x.parent, b) # the sibling
if w.color == RED:
self.say(f" case 1: sibling {w.key} is red; recolour and rotate {a} at {x.parent.key}")
w.color = BLACK; x.parent.color = RED
self.rotate(x.parent, a); w = getattr(x.parent, b)
if getattr(w, a).color == BLACK and getattr(w, b).color == BLACK:
self.say(f" case 2: sibling {w.key} has two black children; recolour {w.key} red, move up to {x.parent.key}")
w.color = RED; x = x.parent
else:
if getattr(w, b).color == BLACK:
self.say(f" case 3: near nephew {getattr(w, a).key} is red; rotate {b} at {w.key}")
getattr(w, a).color = BLACK; w.color = RED
self.rotate(w, b); w = getattr(x.parent, b)
self.say(f" case 4: far nephew {getattr(w, b).key} is red; rotate {a} at {x.parent.key}, done")
w.color = x.parent.color
x.parent.color = BLACK; getattr(w, b).color = BLACK
self.rotate(x.parent, a); x = self.root
x.color = BLACK
def check(self):
def walk(x, lo, hi):
if x is self.nil: return 1
assert (lo is None or lo < x.key) and (hi is None or x.key < hi)
if x.color == RED: assert x.left.color == BLACK and x.right.color == BLACK
for c in (x.left, x.right): assert c is self.nil or c.parent is x
bl, br = walk(x.left, lo, x.key), walk(x.right, x.key, hi)
assert bl == br
return bl + (x.color == BLACK)
assert self.root.color == BLACK
return walk(self.root, None, None) - 1
def show(t, x):
if x is t.nil: return "-"
s = f"{x.key}{x.color}"
return s if x.left is t.nil and x.right is t.nil else f"{s}({show(t, x.left)}, {show(t, x.right)})"
t = RBTree()
t.say = print
for k in [35, 70, 90, 10, 25, 65, 75, 40, 5]:
t.insert(k)
print("start:", show(t, t.root))
for k in [5, 90, 65, 10, 70]:
z = t.find(k)
print(f"delete {k} ({'red' if z.color == RED else 'black'}):")
t.delete(z)
t.check()
print(" ->", show(t, t.root))start: 70B(25R(10B(5R, -), 40B(35R, 65R)), 90B(75R, -))
delete 5 (red):
-> 70B(25R(10B, 40B(35R, 65R)), 90B(75R, -))
delete 90 (black):
-> 70B(25R(10B, 40B(35R, 65R)), 75B)
delete 65 (red):
-> 70B(25R(10B, 40B(35R, -)), 75B)
delete 10 (black):
case 3: near nephew 35 is red; rotate right at 40
case 4: far nephew 40 is red; rotate left at 25, done
-> 70B(35R(25B, 40B), 75B)
delete 70 (black):
case 1: sibling 35 is red; recolour and rotate right at 75
case 2: sibling 40 has two black children; recolour 40 red, move up to 75
-> 35B(25B, 75B(40R, -))
Testing on many inputs
Deletion has many paths through its code, so the test is thorough: 60 trees, each under 250 random insertions and deletions, with all five properties, the order, the parent pointers and the key set checked after every single operation. It also records the most rotations any deletion made.
import random
RED, BLACK = "R", "B"
class Node:
__slots__ = ("key", "color", "left", "right", "parent")
def __init__(self, key, color, nil):
self.key, self.color, self.left, self.right, self.parent = key, color, nil, nil, nil
class RBTree:
def __init__(self):
self.nil = Node(None, BLACK, None)
self.root, self.rotations = self.nil, 0
def rotate(self, x, d):
nil, o = self.nil, ("right" if d == "left" else "left")
y = getattr(x, o)
setattr(x, o, getattr(y, d))
if getattr(y, d) is not nil: getattr(y, d).parent = x
y.parent = x.parent
if x.parent is nil: self.root = y
elif x is x.parent.left: x.parent.left = y
else: x.parent.right = y
setattr(y, d, x)
x.parent = y
self.rotations += 1
def insert(self, key):
z, y, x = Node(key, RED, self.nil), self.nil, self.root
while x is not self.nil:
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is self.nil: self.root = z
elif key < y.key: y.left = z
else: y.right = z
while z.parent.color == RED:
p = z.parent; g = p.parent
a, b = ("left", "right") if p is g.left else ("right", "left")
u = getattr(g, b)
if u.color == RED:
p.color = u.color = BLACK; g.color = RED; z = g; continue
if z is getattr(p, b):
z = p; self.rotate(z, a); p = z.parent
p.color = BLACK; g.color = RED; self.rotate(g, b)
self.root.color = BLACK
def find(self, k):
x = self.root
while x is not self.nil and x.key != k:
x = x.left if k < x.key else x.right
return x
def transplant(self, u, v):
if u.parent is self.nil: self.root = v
elif u is u.parent.left: u.parent.left = v
else: u.parent.right = v
v.parent = u.parent
def delete(self, z):
nil = self.nil
y, y_color = z, z.color
if z.left is nil:
x = z.right; self.transplant(z, z.right)
elif z.right is nil:
x = z.left; self.transplant(z, z.left)
else:
y = z.right
while y.left is not nil: y = y.left
y_color, x = y.color, y.right
if y is not z.right:
self.transplant(y, y.right)
y.right = z.right; y.right.parent = y
else:
x.parent = y
self.transplant(z, y)
y.left = z.left; y.left.parent = y; y.color = z.color
if y_color == BLACK:
while x is not self.root and x.color == BLACK:
a, b = ("left", "right") if x is x.parent.left else ("right", "left")
w = getattr(x.parent, b)
if w.color == RED:
w.color = BLACK; x.parent.color = RED
self.rotate(x.parent, a); w = getattr(x.parent, b)
if getattr(w, a).color == BLACK and getattr(w, b).color == BLACK:
w.color = RED; x = x.parent
else:
if getattr(w, b).color == BLACK:
getattr(w, a).color = BLACK; w.color = RED
self.rotate(w, b); w = getattr(x.parent, b)
w.color = x.parent.color
x.parent.color = BLACK; getattr(w, b).color = BLACK
self.rotate(x.parent, a); x = self.root
x.color = BLACK
def keys(self):
"""inorder keys, asserting every red-black property on the way"""
out = []
def walk(x, lo, hi):
if x is self.nil: return 1
assert (lo is None or lo < x.key) and (hi is None or x.key < hi)
if x.color == RED: assert x.left.color == BLACK and x.right.color == BLACK
for c in (x.left, x.right): assert c is self.nil or c.parent is x
bl = walk(x.left, lo, x.key); out.append(x.key); br = walk(x.right, x.key, hi)
assert bl == br
return bl + (x.color == BLACK)
assert self.root.color == BLACK and self.nil.color == BLACK
walk(self.root, None, None)
return out
rng = random.Random(99)
deletions, max_rot = 0, 0
for trial in range(60):
t, ref = RBTree(), set()
for step in range(250):
k = rng.randrange(120)
if k in ref and rng.random() < 0.6:
before = t.rotations
t.delete(t.find(k)); ref.remove(k)
deletions += 1
max_rot = max(max_rot, t.rotations - before)
elif k not in ref:
t.insert(k); ref.add(k)
assert t.keys() == sorted(ref)
print(f"60 trees, {deletions} deletions: every property held after every operation")
print(f"most rotations in one deletion: {max_rot}")60 trees, 3986 deletions: every property held after every operation
most rotations in one deletion: 3
In C++
The complete C++ red-black tree with insertion and deletion, nodes in a std::vector and freed slots reused. Index 0 is the sentinel; RB-TRANSPLANT writes its parent field as the pseudocode requires, and the rotations leave it alone. The test runs 200,000 seeded random operations against std::set and checks the properties every 1000 operations.
#include <cstdio>
#include <random>
#include <set>
#include <stdexcept>
#include <vector>
class RBTree {
struct Node { int key = 0; bool red = false; int left = 0, right = 0, parent = 0; };
std::vector<Node> t{Node{}}; // t[0] = nil, always black
std::vector<int> free_;
int root = 0;
int& child(int x, bool right) { return right ? t[x].right : t[x].left; }
void rotate(int x, bool left) { // left: x's right child moves up
int y = child(x, left);
child(x, left) = child(y, !left);
if (child(y, !left) != 0) t[child(y, !left)].parent = x;
t[y].parent = t[x].parent;
if (t[x].parent == 0) root = y;
else if (x == t[t[x].parent].left) t[t[x].parent].left = y;
else t[t[x].parent].right = y;
child(y, !left) = x;
t[x].parent = y;
++rotations;
}
void transplant(int u, int v) { // sets nil's parent too
if (t[u].parent == 0) root = v;
else if (u == t[t[u].parent].left) t[t[u].parent].left = v;
else t[t[u].parent].right = v;
t[v].parent = t[u].parent;
}
int check(int x, long lo, long hi) const {
if (x == 0) return 1;
const Node& n = t[x];
if (n.key <= lo || n.key >= hi) throw std::runtime_error("order");
if (n.red && (t[n.left].red || t[n.right].red)) throw std::runtime_error("red-red");
for (int c : {n.left, n.right}) if (c != 0 && t[c].parent != x) throw std::runtime_error("parent");
int bl = check(n.left, lo, n.key), br = check(n.right, n.key, hi);
if (bl != br) throw std::runtime_error("black height");
return bl + !n.red;
}
public:
long rotations = 0;
int find(int k) const {
int x = root;
while (x != 0 && t[x].key != k) x = k < t[x].key ? t[x].left : t[x].right;
return x;
}
void insert(int key) {
int y = 0, x = root;
while (x != 0) { y = x; x = key < t[x].key ? t[x].left : t[x].right; }
int z;
if (!free_.empty()) { z = free_.back(); free_.pop_back(); } else { z = static_cast<int>(t.size()); t.emplace_back(); }
t[z] = {key, true, 0, 0, y};
if (y == 0) root = z; else if (key < t[y].key) t[y].left = z; else t[y].right = z;
while (t[t[z].parent].red) {
int p = t[z].parent, g = t[p].parent;
bool left = p == t[g].left;
int u = child(g, left);
if (t[u].red) { t[p].red = t[u].red = false; t[g].red = true; z = g; continue; }
if (z == child(p, left)) { z = p; rotate(z, left); p = t[z].parent; }
t[p].red = false; t[g].red = true;
rotate(g, !left);
}
t[root].red = false;
}
void erase(int z) {
int y = z, x;
bool y_red = t[y].red;
if (t[z].left == 0) { x = t[z].right; transplant(z, t[z].right); }
else if (t[z].right == 0) { x = t[z].left; transplant(z, t[z].left); }
else {
y = t[z].right;
while (t[y].left != 0) y = t[y].left;
y_red = t[y].red;
x = t[y].right;
if (y != t[z].right) {
transplant(y, t[y].right);
t[y].right = t[z].right; t[t[y].right].parent = y;
} else t[x].parent = y;
transplant(z, y);
t[y].left = t[z].left; t[t[y].left].parent = y; t[y].red = t[z].red;
}
if (!y_red) {
while (x != root && !t[x].red) {
bool left = x == t[t[x].parent].left; // is x a left child?
int w = child(t[x].parent, left);
if (t[w].red) { // case 1
t[w].red = false; t[t[x].parent].red = true;
rotate(t[x].parent, left); w = child(t[x].parent, left);
}
if (!t[t[w].left].red && !t[t[w].right].red) { t[w].red = true; x = t[x].parent; } // case 2
else {
if (!t[child(w, left)].red) { // case 3: far nephew black
t[child(w, !left)].red = false; t[w].red = true;
rotate(w, !left); w = child(t[x].parent, left);
}
t[w].red = t[t[x].parent].red; // case 4
t[t[x].parent].red = false; t[child(w, left)].red = false;
rotate(t[x].parent, left); x = root;
}
}
t[x].red = false;
}
free_.push_back(z);
}
void verify() const { if (t[root].red || t[0].red) throw std::runtime_error("root or nil red"); check(root, -1, 1L << 40); }
};
int main() {
RBTree tree;
std::set<int> ref;
std::mt19937 rng(99);
long ops = 0;
for (int step = 0; step < 200000; ++step) {
int k = static_cast<int>(rng() % 5000);
bool in_tree = tree.find(k) != 0;
if (in_tree != (ref.count(k) == 1)) { std::printf("disagreement at step %d\n", step); return 1; }
if (in_tree && rng() % 2 == 0) { tree.erase(tree.find(k)); ref.erase(k); ++ops; }
else if (!in_tree) { tree.insert(k); ref.insert(k); ++ops; }
if (step % 1000 == 0) tree.verify();
}
tree.verify();
std::printf("%ld updates agree with std::set; properties hold; final size %zu; %.2f rotations per update\n",
ops, ref.size(), double(tree.rotations) / ops);
}134729 updates agree with std::set; properties hold; final size 3313; 0.39 rotations per update
In practice: Because the fix-ups make rotations, red-black trees change the shape of the tree very little per update, which suits structures with pointers into the tree (iterators of
std::mapstay valid through other insertions and deletions) and persistent variants. AVL trees are more strictly balanced (height at most about ) and search slightly faster, but a deletion can need rotations.
Test yourself
When does RB-DELETE need a fix-up?
- always
- only when the node removed or moved, , was originally black
- only when was red
- only when has two children
In the deletion fix-up, which case can repeat, moving the problem up the tree?
- case 1
- case 2
- case 3
- case 4
At most how many rotations does one red-black deletion make?
- 1
- 2
- 3
Why must RB-TRANSPLANT set v.parent even when is the sentinel?
- To keep the sentinel black
- Because the fix-up starts at , which may be the sentinel, and needs
x.parentto find the sibling - Because the sentinel is the root
- It need not; it is only for speed