Red-Black Insertion
Inserting into a red-black tree starts exactly like inserting into a plain BST: walk down, attach the new node as a leaf. The question is what colour to give it. Coloured black, would add one black node to some paths and not others, breaking property 5 everywhere above it, which is hard to repair. Coloured red, changes no black counts at all. The only properties that can fail are property 4 (if 's parent is red too) and property 2 (if is the root). A loop called the fix-up then pushes the problem up the tree with recolourings, and ends it with at most two rotations.
The properties and the checker come from Red-Black Properties and the Height Bound.
The fix-up cases
While 's parent is red, there is a red-red violation between and . Since the root is black, is not the root, so the grandparent exists, and it is black (the tree was valid before arrived). Assume is a left child of ; the other side is the mirror image. Let be 's right child, the uncle of .
- Case 1: the uncle is red. Recolour and black and red. Every path through had one black node at and now has one black node at or instead, so black counts are unchanged. The violation, if any, has moved two levels up, between and its parent: continue with .
- Case 2: is black and is a right child (an inner child: it lies between and in key order). Rotate left at . Now the old is a left child of , both red, and the situation is case 3 with the roles swapped: set to the old .
- Case 3: is black and is a left child (an outer child). Colour black and red, then rotate right at . Now is the black root of this subtree with two red children and , no red-red edge is left, and every path has the same black count as before. The loop ends.
When the loop ends, colour the root black, which repairs property 2 if case 1 pushed red all the way up.
RB-INSERT-FIXUP(T, z)
1 while z.parent.color == RED
2 p = z.parent, g = p.parent
3 if p == g.left
4 u = g.right
5 if u.color == RED // case 1
6 p.color = BLACK, u.color = BLACK, g.color = RED
7 z = g
8 else
9 if z == p.right // case 2
10 z = p
11 LEFT-ROTATE(T, z)
12 p = z.parent
13 p.color = BLACK, g.color = RED // case 3
14 RIGHT-ROTATE(T, g)
15 else (the same with "left" and "right" exchanged)
16 T.root.color = BLACKWatching it work
The Python version prints the same steps as the animation: the insertion, each fix-up case and the final recolouring of the root. It uses one sentinel node for all NIL leaves and checks all five properties after every insertion.
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) # the shared sentinel T.nil
self.root = self.nil
def rotate(self, x, direction): # "left": x's right child moves up
nil = self.nil
if direction == "left":
y = x.right; x.right = y.left
if y.left is not nil: y.left.parent = x
else:
y = x.left; x.left = y.right
if y.right is not nil: y.right.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
if direction == "left": y.left = x
else: y.right = x
x.parent = y
def insert(self, key, say=print):
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
say(f"insert {key} as a red leaf")
while z.parent.color == RED:
p = z.parent; g = p.parent
left = p is g.left
u = g.right if left else g.left
if u.color == RED:
p.color = u.color = BLACK; g.color = RED
say(f" case 1: parent {p.key} and uncle {u.key} red; recolour them black, {g.key} red; continue at {g.key}")
z = g
continue
if z is (p.right if left else p.left):
say(f" case 2: {z.key} is an inner child; rotate {'left' if left else 'right'} at {p.key}")
z = p
self.rotate(z, "left" if left else "right")
p = z.parent
p.color = BLACK; g.color = RED
say(f" case 3: colour {p.key} black, {g.key} red; rotate {'right' if left else 'left'} at {g.key}")
self.rotate(g, "right" if left else "left")
if self.root.color == RED:
say(f" root {self.root.key} recoloured black")
self.root.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()
for k in [50, 20, 70, 10, 30, 25, 27, 5, 1, 60, 65, 62]:
t.insert(k)
t.check()
print("tree:", show(t, t.root))
print("black-height:", t.check())insert 50 as a red leaf
root 50 recoloured black
insert 20 as a red leaf
insert 70 as a red leaf
insert 10 as a red leaf
case 1: parent 20 and uncle 70 red; recolour them black, 50 red; continue at 50
root 50 recoloured black
insert 30 as a red leaf
insert 25 as a red leaf
case 1: parent 30 and uncle 10 red; recolour them black, 20 red; continue at 20
insert 27 as a red leaf
case 2: 27 is an inner child; rotate left at 25
case 3: colour 27 black, 30 red; rotate right at 30
insert 5 as a red leaf
insert 1 as a red leaf
case 3: colour 5 black, 10 red; rotate right at 10
insert 60 as a red leaf
insert 65 as a red leaf
case 2: 65 is an inner child; rotate left at 60
case 3: colour 65 black, 70 red; rotate right at 70
insert 62 as a red leaf
case 1: parent 60 and uncle 70 red; recolour them black, 65 red; continue at 65
tree: 50B(20R(5B(1R, 10R), 27B(25R, 30R)), 65R(60B(-, 62R), 70B))
black-height: 2
The letter after each key is its colour; the root is still 50, because no rotation happened at the top. Insertions 20, 70, 30, 5 and 60 needed no fix-up at all: their parents were black.
Why it is correct
The loop keeps an invariant. At the start of each iteration:
- is red;
- the tree satisfies all properties except possibly property 4 at (between and its parent) or property 2 (if is the root, which is then red);
- properties 1, 3 and 5 hold everywhere.
It holds initially, because inserting a red leaf changes no black count. Case 1 recolours without changing any black count and moves the possible violation to , which is red: the invariant holds for . Cases 2 and 3 repair everything below 's old position without changing black counts on any path, and leave a black node at the top of the subtree, so no violation remains and the loop stops. The final line fixes property 2.
Cost. The insertion walk is by the height bound. Each iteration of case 1 moves up two levels, so there are iterations, each . Cases 2 and 3 run at most once and end the loop. So insertion takes time and makes at most two rotations, however large the tree.
Testing on many inputs
The test inserts keys in random order, in sorted order (the worst input for a plain BST) and in a zigzag order, checks the properties after every insertion, and records the heights and rotations. Per insertion it also counts the case-1 iterations, which are cheap recolourings.
import math, 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.recolours, self.max_rot = self.nil, 0, 0, 0
def rotate(self, x, direction):
nil = self.nil
if direction == "left":
y = x.right; x.right = y.left
if y.left is not nil: y.left.parent = x
else:
y = x.left; x.left = y.right
if y.right is not nil: y.right.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
if direction == "left": y.left = x
else: y.right = 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
before = self.rotations
while z.parent.color == RED:
p = z.parent; g = p.parent
left = p is g.left
u = g.right if left else g.left
if u.color == RED:
p.color = u.color = BLACK; g.color = RED
self.recolours += 1
z = g
continue
if z is (p.right if left else p.left):
z = p
self.rotate(z, "left" if left else "right")
p = z.parent
p.color = BLACK; g.color = RED
self.rotate(g, "right" if left else "left")
self.root.color = BLACK
self.max_rot = max(self.max_rot, self.rotations - before)
def check(self):
def walk(x, lo, hi):
if x is self.nil: return 1, -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, hl), (br, hr) = walk(x.left, lo, x.key), walk(x.right, x.key, hi)
assert bl == br
return bl + (x.color == BLACK), 1 + max(hl, hr)
assert self.root.color == BLACK
return walk(self.root, None, None)[1]
rng = random.Random(13)
n = 2000
orders = {"random": rng.sample(range(n), n), "sorted": list(range(n)),
"zigzag": [i // 2 if i % 2 == 0 else n - 1 - i // 2 for i in range(n)]}
for name, keys in orders.items():
t = RBTree()
for i, k in enumerate(keys, 1):
t.insert(k)
if i % 100 == 0 or i == n:
h = t.check() # full check every 100 insertions
print(f"{name:6}: height {h:2} (lg n = {math.log2(n):.1f}, bound 2 lg(n+1) = {2 * math.log2(n + 1):.1f}), "
f"rotations {t.rotations / n:.2f} per insert (max {t.max_rot}), case-1 recolourings {t.recolours / n:.2f} per insert")
for trial in range(200): # small trees, checked after every single insertion
t = RBTree()
for k in rng.sample(range(100), rng.randint(1, 40)):
t.insert(k); t.check()
print("200 more random trees checked after every insertion")random: height 13 (lg n = 11.0, bound 2 lg(n+1) = 21.9), rotations 0.59 per insert (max 2), case-1 recolourings 0.52 per insert
sorted: height 18 (lg n = 11.0, bound 2 lg(n+1) = 21.9), rotations 0.99 per insert (max 1), case-1 recolourings 0.99 per insert
zigzag: height 18 (lg n = 11.0, bound 2 lg(n+1) = 21.9), rotations 1.49 per insert (max 2), case-1 recolourings 0.99 per insert
200 more random trees checked after every insertion
On random input the height is 13, close to . Sorted and zigzag input, which would make a plain BST a path of height 1999, give height 18. Sorted insertions always land at the right edge of the tree, where red and black nodes end up alternating, the shape that makes the factor 2 in the bound necessary; even so the height stays below , as it must. No insertion made more than two rotations, and on average there were 0.6 to 1.5 per insertion.
In C++
The C++ red-black tree stores nodes in a std::vector with index 0 as the black sentinel. It inserts 100,000 seeded random keys, checks the properties at the end, compares the contents with std::set (itself a red-black tree in GCC's library) and reports the height.
#include <cmath>
#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] is the black sentinel nil
int root = 0;
void rotate_left(int x) {
int y = t[x].right;
t[x].right = t[y].left;
if (t[y].left != 0) t[t[y].left].parent = x;
link(t[x].parent, x, y);
t[y].left = x; t[x].parent = y;
}
void rotate_right(int x) {
int y = t[x].left;
t[x].left = t[y].right;
if (t[y].right != 0) t[t[y].right].parent = x;
link(t[x].parent, x, y);
t[y].right = x; t[x].parent = y;
}
void link(int parent, int old, int now) { // now takes old's place under parent
t[now].parent = parent;
if (parent == 0) root = now;
else if (t[parent].left == old) t[parent].left = now;
else t[parent].right = now;
}
int check(int x, long lo, long hi, int& height, int depth) const {
if (x == 0) { if (depth - 1 > height) height = depth - 1; 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");
int bl = check(n.left, lo, n.key, height, depth + 1), br = check(n.right, n.key, hi, height, depth + 1);
if (bl != br) throw std::runtime_error("black height");
return bl + !n.red;
}
public:
long rotations = 0;
bool insert(int key) {
int y = 0, x = root;
while (x != 0) {
if (key == t[x].key) return false;
y = x; x = key < t[x].key ? t[x].left : t[x].right;
}
t.push_back({key, true, 0, 0, y});
int z = static_cast<int>(t.size()) - 1;
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 = left ? t[g].right : t[g].left;
if (t[u].red) { // case 1
t[p].red = t[u].red = false; t[g].red = true;
z = g;
continue;
}
if (z == (left ? t[p].right : t[p].left)) { // case 2
z = p;
if (left) rotate_left(z); else rotate_right(z);
++rotations;
p = t[z].parent;
}
t[p].red = false; t[g].red = true; // case 3
if (left) rotate_right(g); else rotate_left(g);
++rotations;
}
t[root].red = false;
return true;
}
int checked_height() const {
if (t[root].red) throw std::runtime_error("red root");
int h = -1;
check(root, -1, 1L << 40, h, 0);
return h;
}
void inorder(int x, std::vector<int>& out) const {
if (x == 0) return;
inorder(t[x].left, out); out.push_back(t[x].key); inorder(t[x].right, out);
}
std::vector<int> keys() const { std::vector<int> v; inorder(root, v); return v; }
};
int main() {
RBTree tree;
std::set<int> ref;
std::mt19937 rng(13);
while (ref.size() < 100000) {
int k = static_cast<int>(rng() % 10000000);
if (tree.insert(k) != ref.insert(k).second) { std::printf("disagreement\n"); return 1; }
}
int h = tree.checked_height();
bool same = tree.keys() == std::vector<int>(ref.begin(), ref.end());
std::printf("n = %zu: properties hold, height %d (2 lg(n+1) = %.1f), same keys as std::set: %s, rotations per insert %.2f\n",
ref.size(), h, 2 * std::log2(ref.size() + 1.0), same ? "yes" : "no", tree.rotations / 100000.0);
}n = 100000: properties hold, height 19 (2 lg(n+1) = 33.2), same keys as std::set: yes, rotations per insert 0.58
In practice:
std::map::insertin GCC's library (_Rb_tree_insert_and_rebalance) and Java'sTreeMap.fixAfterInsertionare this same fix-up, written with explicit parent pointers. The Linux kernel'srbtree.hexposes it to callers in two steps: the caller links the new node in place, then callsrb_insert_colorto run the fix-up.
Test yourself
Why is a newly inserted node coloured red?
- Red nodes are cheaper to store
- A red node changes no black counts, so only property 4 or 2 can fail, and those are local
- The root must be red
- To make the tree look balanced
In case 1 (red uncle), what happens next?
- One rotation and the loop ends
- Parent and uncle become black, the grandparent red, and the loop continues two levels up at the grandparent
- The new node is recoloured black
- The tree is rebuilt
At most how many rotations does one red-black insertion perform?
- 1
- 2
- 3
The parent of is a left child, the uncle is black, and is 's right child. Which case applies?
- case 1
- case 2: rotate left at , then case 3
- case 3 directly
- no fix-up is needed