A red-black tree is a binary search tree whose nodes carry one bit of color, and the color rules are enough to keep the height logarithmic without storing a height at every node. Insertion and deletion restore the rules with recoloring and rotations, and the result is the tree behind the ordered maps most programmers use. This article implements the full CLRS insert and delete in C++ and Java, measures height and rotations against an AVL tree on the same input, and counts the comparisons inside std::map and TreeMap.
On 100,000 keys in ascending order, the red-black tree reached a height of 30 edges with 99,969 rotations, against 16 edges and 99,983 rotations for an AVL tree. On the same keys in random order, both trees ended at 19 edges, and the red-black tree needed 16 percent fewer rotations. Java’s TreeMap made exactly the same number of comparisons per lookup as the article’s tree, 16.10 at that size. All programs were built and tested with GCC 13.3, Clang 18.1.3, MSVC 19.44 and JDK 21 and 27.
What Is a Red-Black Tree?
A red-black tree is a binary search tree in which every node is red or black, the root is black, no red node has a red child, and every path from a node down to a null leaf contains the same number of black nodes. Those rules keep the height within 2 log2(n + 1), so search, insert and delete are O(log n) in the worst case, and updates restore the rules with recoloring and a few rotations.
The structure exists for the same reason as the AVL tree: a plain BST has no height guarantee, and sorted input turns it into a chain. The red-black tree replaces AVL’s height-difference rule with a looser color rule. Both trees need at most two rotations per insertion. The difference shows elsewhere: a red-black insertion often fixes a violation by recoloring alone, and a deletion needs at most three rotations, where an AVL deletion can rotate at every level on the way to the root.
The color rules are worth reading twice, because every fixup case follows from them. A red node’s children must be black, so the longest root-to-leaf path, alternating red and black, is at most twice the shortest, which is all black. That gives the height bound. The insert and delete fixups are the local operations that restore the rules after a change.
The tree is an ordered set: in-order traversal is sorted, duplicates are rejected, and search is the ordinary BST descent. The Binary Search Tree article covers those operations, and the B-Tree article covers the multi-way alternative for block storage. What this article adds is the coloring, the two fixups and the measurements.
How This Was Measured
| Setting | Value |
|---|---|
| Date tested | December 5, 2026 |
| Hardware | Intel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300 |
| Operating system | Ubuntu 24.04.5 under WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39, and Windows 11 for the MSVC and JDK 27 runs |
| C++ toolchain | g++ 13.3 and clang++ 18.1.3 at -O2 through CMake Release, MSVC 19.44 at /W4 /WX /permissive- |
| Java toolchain | JDK 27 on Windows for the captured output, OpenJDK 21 on Ubuntu for a byte-identical rerun, javac --release 17 |
| Height experiment | N of 100, 1,000, 10,000 and 100,000. Sorted keys 1..N and one fixed xorshift64 permutation, into a red-black tree and an insert-only AVL tree |
| Map comparison | Sorted insertion of 1..N into std::map or TreeMap with a counting comparator, then a lookup of every key. The article’s tree gets the same treatment |
| What is recorded | Height in edges, single-rotation counts (a double rotation counts as two), and average comparisons per lookup |
| Statistic | Deterministic integers and exact averages, identical on every run and in both languages |
The numbers are counts, so they reproduce on any machine. A counting comparator is the only portable way to look inside a standard container: it sees every key comparison the map performs, and the average over all lookups shows how deep the tree behaves without relying on the library’s internal layout.
The Five Properties and What They Buy
The five rules are: every node is red or black, the root is black, every null leaf is black, a red node has only black children, and every path from a node to a null leaf below it has the same number of black nodes. The first three are conventions, the fourth prevents long red runs, and the fifth defines the black height. Together they bound the height at 2 log2(n + 1).
That bound is looser than AVL’s 1.44 log2 n, and the looseness is deliberate. A red-black tree accepts a longer worst-case path in exchange for cheaper updates. The measured heights show the cost on sorted input, and the rotation counts on random input show the benefit.
A useful way to read the tree is that the black nodes form a perfectly balanced skeleton, and each red node is an extra key tucked in beside a black parent. That is exactly the shape of a 2-3-4 tree, where a black node and its red children form one node of up to three keys. Two reds in a row would make a node of four or more keys, which the shape does not allow.
Insertion: Recoloring and Three Cases
Insertion is the ordinary BST descent, a new red node, and a fixup loop that runs while the parent is red. The uncle’s color decides the case. When the uncle is red, the parent and uncle turn black, the grandparent turns red, and the loop continues two levels up. When the uncle is black, one rotation fixes a new node on the outer side and two rotations fix one on the inner side, and the loop ends. Finally, the root is forced black, which is the easy line to forget.
The recoloring case is why insertion is cheap. It changes colors only, never pointers, and although it can repeat up the tree, each repetition climbs two levels, so it is bounded by the height. The rotation cases use the same left and right rotations as any balanced tree.
Deletion and the Double-Black Problem
Deletion starts with the ordinary BST cases. If the removed node was red, the black heights are unchanged and no fixup is needed. If it was black, every path through it is now one black node short, and the fixup carries an extra black up the tree until it can be absorbed. A red sibling rotates and recolors to become a black-sibling case. A black sibling with two black children pushes the extra black up to the parent. A black sibling with a red child ends the fixup with one or two rotations.
A node with two children takes its in-order successor’s key, and the successor is removed instead. The successor has at most one child, so the structural step is always simple, and the fixup carries the difficulty. The tests delete keys in every position and check all five properties after each operation, and the deletion pitfalls fail that same check.
The Height Bound and What 2 log n Means
With black height b, a path alternates at most one red between blacks, so the height is at most 2b. A subtree whose root has black height b contains at least 2^b – 1 nodes, so b is at most log2(n + 1). Together they give a height of at most 2 log2(n + 1): a factor of two above the ideal and about 1.4 times AVL’s bound.
The bound is a worst-case guarantee, and how close a tree comes depends on the input. Sorted insertion pushes a red-black tree near it: 30 edges at 100,000 keys against a bound of 33.2. Random insertion stays far below: 19 edges, the same as AVL. The search path is always a small multiple of log2 n, and updates need only a few rotations, which is why standard libraries choose this structure for ordered maps. The Skip List article measures the randomized alternative that Redis uses for sorted sets.
Red-Black Tree Implementation in C++
The C++ version is a class over raw Node* pointers with a shared nil sentinel that is always black. Insertion descends, attaches a red node and calls the fixup. Deletion finds the node, moves the successor’s key into it when needed, unlinks the successor, and calls the delete fixup on the child that took its place. The rotations and fixups are private helpers.
void rotate_left(Node* x) noexcept
{
Node* y = x->right;
x->right = y->left;
if (y->left != &nil_)
y->left->parent = x;
y->parent = x->parent;
if (x->parent == &nil_)
root_ = y;
else if (x == x->parent->left)
x->parent->left = y;
else
x->parent->right = y;
y->left = x;
x->parent = y;
++rotations_;
}
// CLRS RIGHT-ROTATE, the mirror image of rotate_left.
void rotate_right(Node* x) noexcept
{
Node* y = x->left;
x->left = y->right;
if (y->right != &nil_)
y->right->parent = x;
y->parent = x->parent;
if (x->parent == &nil_)
root_ = y;
else if (x == x->parent->right)
x->parent->right = y;
else
x->parent->left = y;
y->right = x;
x->parent = y;
++rotations_;
}
void insert_fixup(Node* node) noexcept
{
while (is_red(node->parent)) {
Node* parent = node->parent;
Node* grandparent = parent->parent;
if (parent == grandparent->left) {
Node* uncle = grandparent->right;
if (is_red(uncle)) {
parent->color = Color::Black;
uncle->color = Color::Black;
grandparent->color = Color::Red;
node = grandparent;
} else {
if (node == parent->right) {
node = parent;
rotate_left(node);
parent = node->parent;
grandparent = parent->parent;
}
parent->color = Color::Black;
grandparent->color = Color::Red;
rotate_right(grandparent);
}
} else {
Node* uncle = grandparent->left;
if (is_red(uncle)) {
parent->color = Color::Black;
uncle->color = Color::Black;
grandparent->color = Color::Red;
node = grandparent;
} else {
if (node == parent->left) {
node = parent;
rotate_right(node);
parent = node->parent;
grandparent = parent->parent;
}
parent->color = Color::Black;
grandparent->color = Color::Red;
rotate_left(grandparent);
}
}
}
root_->color = Color::Black;
}
void erase_fixup(Node* node) noexcept
{
while (node != root_ && !is_red(node)) {
if (node == node->parent->left) {
Node* sibling = node->parent->right;
if (is_red(sibling)) {
sibling->color = Color::Black;
node->parent->color = Color::Red;
rotate_left(node->parent);
sibling = node->parent->right;
}
if (!is_red(sibling->left) && !is_red(sibling->right)) {
sibling->color = Color::Red;
node = node->parent;
} else {
if (!is_red(sibling->right)) {
sibling->left->color = Color::Black;
sibling->color = Color::Red;
rotate_right(sibling);
sibling = node->parent->right;
}
sibling->color = node->parent->color;
node->parent->color = Color::Black;
sibling->right->color = Color::Black;
rotate_left(node->parent);
node = root_;
}
} else {
Node* sibling = node->parent->left;
if (is_red(sibling)) {
sibling->color = Color::Black;
node->parent->color = Color::Red;
rotate_right(node->parent);
sibling = node->parent->left;
}
if (!is_red(sibling->left) && !is_red(sibling->right)) {
sibling->color = Color::Red;
node = node->parent;
} else {
if (!is_red(sibling->left)) {
sibling->right->color = Color::Black;
sibling->color = Color::Red;
rotate_left(sibling);
sibling = node->parent->left;
}
sibling->color = node->parent->color;
node->parent->color = Color::Black;
sibling->left->color = Color::Black;
rotate_right(node->parent);
node = root_;
}
}
}
node->color = Color::Black;
nil_.color = Color::Black;
}
Output:
red-black tree: insert, delete and rotations
insert 10, 20, 30 -> root 20, height 1, rotations 1
insert 40, 50 -> root 20, height 2, rotations 2
insert 25 -> root 20, height 3, rotations 2
inorder: 10 20 25 30 40 50
delete 25 -> root 20, height 2, size 5
delete 50 -> root 20, height 2, size 4
inorder: 10 20 30 40
search 30 -> true, search 25 -> false
final height 2, size 4, rotations 2
Red-Black Tree Implementation in Java
The Java version is a class with an inner Node and one shared nil sentinel. It runs the same CLRS insert and delete, keeping the sentinel’s parent pointer up to date where the delete fixup needs it. Its diagnostics mirror the C++ ones: height, black height, size, the rotation counter, an in-order list and the property check the tests use.
public boolean insert(int key) {
Node parent = nil;
Node current = root;
while (current != nil) {
comparisons++;
parent = current;
if (key < current.key) {
current = current.left;
} else if (key > current.key) {
current = current.right;
} else {
return false; // the key is already in the tree
}
}
Node node = new Node(key);
node.left = nil;
node.right = nil;
node.parent = parent;
node.red = RED;
if (parent == nil) {
root = node;
} else if (key < parent.key) {
parent.left = node;
} else {
parent.right = node;
}
size++;
insertFixup(node);
return true;
}
private void insertFixup(Node node) {
while (node.parent.red) {
if (node.parent == node.parent.parent.left) {
Node uncle = node.parent.parent.right;
if (uncle.red) {
node.parent.red = BLACK;
uncle.red = BLACK;
node.parent.parent.red = RED;
node = node.parent.parent;
} else {
if (node == node.parent.right) {
node = node.parent;
rotateLeft(node);
}
node.parent.red = BLACK;
node.parent.parent.red = RED;
rotateRight(node.parent.parent);
}
} else {
Node uncle = node.parent.parent.left;
if (uncle.red) {
node.parent.red = BLACK;
uncle.red = BLACK;
node.parent.parent.red = RED;
node = node.parent.parent;
} else {
if (node == node.parent.left) {
node = node.parent;
rotateRight(node);
}
node.parent.red = BLACK;
node.parent.parent.red = RED;
rotateLeft(node.parent.parent);
}
}
}
root.red = BLACK;
}
private void deleteFixup(Node node) {
while (node != root && !node.red) {
if (node == node.parent.left) {
Node sibling = node.parent.right;
if (sibling.red) {
sibling.red = BLACK;
node.parent.red = RED;
rotateLeft(node.parent);
sibling = node.parent.right;
}
if (!sibling.left.red && !sibling.right.red) {
sibling.red = RED;
node = node.parent;
} else {
if (!sibling.right.red) {
sibling.left.red = BLACK;
sibling.red = RED;
rotateRight(sibling);
sibling = node.parent.right;
}
sibling.red = node.parent.red;
node.parent.red = BLACK;
sibling.right.red = BLACK;
rotateLeft(node.parent);
node = root;
}
} else {
Node sibling = node.parent.left;
if (sibling.red) {
sibling.red = BLACK;
node.parent.red = RED;
rotateRight(node.parent);
sibling = node.parent.left;
}
if (!sibling.right.red && !sibling.left.red) {
sibling.red = RED;
node = node.parent;
} else {
if (!sibling.left.red) {
sibling.right.red = BLACK;
sibling.red = RED;
rotateLeft(sibling);
sibling = node.parent.left;
}
sibling.red = node.parent.red;
node.parent.red = BLACK;
sibling.left.red = BLACK;
rotateRight(node.parent);
node = root;
}
}
}
node.red = BLACK;
}
The Java demo prints the same ten lines as the C++ program, byte for byte.
Measured: Height and Rotations Against AVL
The height experiment builds the red-black tree and an insert-only AVL tree from the same key sequence, once ascending and once in the fixed pseudo-random order, and records both heights and both rotation counts.
int main()
{
const int sizes[] = {100, 1000, 10000, 100000};
// The AVL article's measured sorted-order results, repeated here as a check
// that this helper really is the same tree the AVL article describes.
const int expected_avl_heights[] = {6, 9, 13, 16};
const long long expected_avl_rotations[] = {93, 990, 9986, 99983};
std::uint64_t state = kSeed;
std::vector<Row> rows;
bool ok = true;
for (std::size_t index = 0; index < 4; ++index) {
const int n = sizes[index];
// The two orders: ascending 1..N and the shared pseudo-random
// permutation drawn from the carried generator state.
std::vector<int> sorted_keys(static_cast<std::size_t>(n));
for (int i = 0; i < n; ++i)
sorted_keys[static_cast<std::size_t>(i)] = i + 1;
const std::vector<int> random_keys = shuffled_keys(n, state);
const std::vector<int>* orders[] = {&sorted_keys, &random_keys};
const char* order_names[] = {"sorted", "random"};
for (std::size_t order_index = 0; order_index < 2; ++order_index) {
const std::vector<int>& keys = *orders[order_index];
RedBlackTree tree;
for (const int key : keys)
tree.insert(key);
InsertOnlyAvl avl;
for (const int key : keys)
avl.insert(key);
rows.push_back(Row{n, order_names[order_index], tree.height(),
tree.rotations(), avl.height(), avl.rotations()});
if (tree.size() != static_cast<std::size_t>(n)) {
std::cerr << "N=" << n << " " << order_names[order_index]
<< ": the red-black tree lost keys\n";
ok = false;
}
if (!tree.check_invariants()) {
std::cerr << "N=" << n << " " << order_names[order_index]
<< ": the red-black invariants do not hold\n";
ok = false;
}
const double rb_bound = 2.0 * std::log2(static_cast<double>(n) + 1.0);
if (static_cast<double>(tree.height()) > rb_bound) {
std::cerr << "N=" << n << " " << order_names[order_index]
<< ": red-black height " << tree.height()
<< " exceeds 2 log2(n + 1) = " << rb_bound << '\n';
ok = false;
}
if (tree.black_height() < 0) {
std::cerr << "N=" << n << " " << order_names[order_index]
<< ": the black-height diagnostic is negative\n";
ok = false;
}
if (!avl.check_invariants()) {
std::cerr << "N=" << n << " " << order_names[order_index]
<< ": the AVL invariants do not hold\n";
ok = false;
}
if (order_index == 0) {
if (avl.height() != expected_avl_heights[index]) {
std::cerr << "N=" << n << " sorted: AVL height " << avl.height()
<< " does not match the AVL article's "
<< expected_avl_heights[index] << '\n';
ok = false;
}
if (avl.rotations() != expected_avl_rotations[index]) {
std::cerr << "N=" << n << " sorted: AVL rotations "
<< avl.rotations() << " do not match the AVL article's "
<< expected_avl_rotations[index] << '\n';
ok = false;
}
}
}
}
print_header();
for (const Row& row : rows)
print_row(row);
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
Output (C++, identical in Java):
N order rb_height rb_rotations avl_height avl_rotations
100 sorted 10 89 6 93
100 random 7 65 7 74
1000 sorted 16 983 9 990
1000 random 11 572 11 691
10000 sorted 23 9976 13 9986
10000 random 15 5898 15 7130
100000 sorted 30 99969 16 99983
100000 random 19 58838 19 70221
On sorted input the red-black heights are 10, 16, 23 and 30 against AVL’s 6, 9, 13 and 16, so the red-black tree is 4 to 14 edges taller. Every row stays under the 2 log2(N + 1) bound of 13.3, 19.9, 26.6 and 33.2. Both trees rotate almost once per insertion on sorted input, 99,969 against 99,983 at 100,000 keys, so sorted input gives red-black no update advantage.
On the random permutation the heights are identical in every row: 7, 11, 15 and 19. The rotations are not. The red-black tree needs 65, 572, 5,898 and 58,838 against AVL’s 74, 691, 7,130 and 70,221, which is 12 to 17 percent fewer, because the looser rule lets more insertions finish by recoloring. The sorted AVL rows reproduce the AVL Tree article‘s numbers exactly, which cross-checks the experiment.
Measured: The Standard Maps
The map experiment inserts the sorted keys into std::map, or TreeMap in Java, with a comparator that counts every call. It then looks up every key and divides the comparison total by N. The article’s own tree gets the same treatment, so each table compares a standard container with the explicit implementation on identical work.
The documentation states what the containers are. The Java TreeMap documentation calls it a red-black tree based map. The C++ standard only fixes the complexity, and cppreference notes that maps are usually implemented as red-black trees, as libstdc++ does. Wikipedia covers the structure’s history.
int main()
{
const int sizes[] = {100, 1000, 10000, 100000};
bool ok = true;
std::cout << "std::map and the red-black tree, sorted insertion, lookup comparisons\n";
std::cout << std::left << std::setw(9) << "N" << std::setw(15) << "map_build_cmp"
<< std::setw(16) << "map_lookup_cmp" << std::setw(14) << "rb_build_cmp"
<< "rb_lookup_cmp" << '\n';
for (const int n : sizes) {
// Build both trees from the ascending keys 1..N.
long long map_comparisons = 0;
std::map<int, bool, CountingLess> map(CountingLess{&map_comparisons});
for (int key = 1; key <= n; ++key)
map.insert(std::pair<int, bool>(key, true));
const long long map_build = map_comparisons;
RedBlackTree tree;
for (int key = 1; key <= n; ++key)
tree.insert(key);
const long long rb_build = tree.comparisons();
// One successful lookup of every key, counted separately.
map_comparisons = 0;
for (int key = 1; key <= n; ++key) {
if (map.find(key) == map.end()) {
std::cerr << "N=" << n << ": std::map lost key " << key << '\n';
ok = false;
}
}
const long long map_lookup = map_comparisons;
tree.reset_comparisons();
for (int key = 1; key <= n; ++key) {
if (!tree.contains(key)) {
std::cerr << "N=" << n << ": the red-black tree lost key " << key << '\n';
ok = false;
}
}
const long long rb_lookup = tree.comparisons();
const double divisor = static_cast<double>(n);
const double map_average = static_cast<double>(map_lookup) / divisor;
const double rb_average = static_cast<double>(rb_lookup) / divisor;
std::cout << std::left << std::setw(9) << n << std::setw(15) << map_build
<< std::fixed << std::setprecision(2) << std::setw(16) << map_average
<< std::setw(14) << rb_build << rb_average << '\n';
}
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
Output (C++):
std::map and the red-black tree, sorted insertion, lookup comparisons
N map_build_cmp map_lookup_cmp rb_build_cmp rb_lookup_cmp
100 1007 8.09 809 6.20
1000 16479 11.39 14481 9.41
10000 231381 14.88 211383 12.89
100000 2972387 18.10 2772389 16.10
Output (Java, the same experiment through TreeMap):
TreeMap and the red-black tree, sorted insertion, lookup comparisons
N map_build_cmp map_lookup_cmp rb_build_cmp rb_lookup_cmp
100 810 6.20 809 6.20
1000 14482 9.41 14481 9.41
10000 211384 12.89 211383 12.89
100000 2772390 16.10 2772389 16.10
Java’s TreeMap matches the article’s tree exactly on lookups, 6.20, 9.41, 12.89 and 16.10 comparisons, and makes one extra comparison during the build, a type check on the first key. On sorted input that is strong evidence that TreeMap builds the same tree: a different shape would give different lookup counts.
std::map counts differently. Its builds use exactly 2(N – 1) more comparisons than the article’s tree: two extra comparator calls on every insertion after the first, part of libstdc++’s unique-key insertion path. Its lookups cost about two comparisons more, 18.10 against 16.10 at 100,000 keys, because find walks to the bottom of the tree instead of stopping at the match and then makes one more comparison to confirm the key. The growth is the same logarithmic profile.
Five Ways a Red-Black Tree Passes a Quick Test and Still Fails
Each program below compiles cleanly and keeps a valid search order, so lookups still work, until the property check names the rule it breaks. The three C++ pitfalls are in the C++ repository and the two Java pitfalls in the Java repository, and the workflows rerun each one and check its output line.
1. A Root Left Red
void insert_fixup(Node*& root, Node* z, bool force_root_black)
{
while (is_red(z->parent) && z->parent->parent != nullptr) {
Node* parent = z->parent;
Node* grandparent = parent->parent;
if (parent == grandparent->left) {
Node* uncle = grandparent->right;
if (is_red(uncle)) {
parent->red = false;
uncle->red = false;
grandparent->red = true;
z = grandparent;
} else {
if (z == parent->right) {
z = parent;
rotate_left(root, z);
parent = z->parent;
grandparent = parent->parent;
}
parent->red = false;
grandparent->red = true;
rotate_right(root, grandparent);
}
} else {
Node* uncle = grandparent->left;
if (is_red(uncle)) {
parent->red = false;
uncle->red = false;
grandparent->red = true;
z = grandparent;
} else {
if (z == parent->left) {
z = parent;
rotate_right(root, z);
parent = z->parent;
grandparent = parent->parent;
}
parent->red = false;
grandparent->red = true;
rotate_left(root, grandparent);
}
}
}
if (force_root_black)
root->red = false;
}
Output:
red_root_after_insert: the insert fixup recolours the grandparent but never forces the root black
correct fixup after 10, 20, 30, 40: root 20, height 2, root colour black
missing root-black line after 10, 20, 30, 40: root 20, height 2, root colour red
violated property: the root of a red-black tree must be black
The fixup recolors the grandparent but never forces the root black at the end of the insert. After 10, 20, 30 and 40 the root is 20 and red, which breaks the root rule, and the property walk names it. The fix is one line at the end of every insert: set the root black.
2. An Uncle That Is Ignored
void insert_fixup(Node*& root, Node* z)
{
while (is_red(z->parent)) {
Node* parent = z->parent;
Node* grandparent = parent->parent;
if (parent == grandparent->left) {
if (z == parent->right) {
z = parent;
rotate_left(root, z);
parent = z->parent;
grandparent = parent->parent;
}
parent->red = false;
grandparent->red = true;
rotate_right(root, grandparent);
} else {
if (z == parent->left) {
z = parent;
rotate_right(root, z);
parent = z->parent;
grandparent = parent->parent;
}
parent->red = false;
grandparent->red = true;
rotate_left(root, grandparent);
}
}
root->red = false;
}
Output:
uncle_ignored: the insert fixup rotates on every red parent without checking whether the uncle is red
after 10, 20, 30, 40: root 30, height 2, root colour black
first red-red violation: parent 20 has red child 10
black counts on the root-to-nil paths: 0 0 0 0 0 (a rotation keeps them equal)
violated property: a red node must have two black children
The fixup rotates on every red parent without checking whether the uncle is red. After 10, 20, 30 and 40 the black counts printed for every path are equal, so the black-height rule holds. The red rule does not: parent 20 has red child 10. A red uncle calls for recoloring, and rotating instead leaves two reds in a row.
3. A Delete Without Fixup
void erase_leaf_without_fixup(Node*& root, int key)
{
Node* node = root;
while (node != nullptr) {
if (key < node->key)
node = node->left;
else if (key > node->key)
node = node->right;
else
break;
}
if (node == nullptr)
return;
Node* parent = node->parent;
if (parent == nullptr)
root = nullptr;
else if (node == parent->left)
parent->left = nullptr;
else
parent->right = nullptr;
delete node;
}
Output:
delete_fixup_missing: deleting a black leaf without the delete fixup leaves unequal black heights
before the delete: root 20, size 5
after deleting black leaf 10: root 20, size 4
black height on the left root-to-nil path: 0
black height on the right root-to-nil path: 1
black heights on every root-to-nil path: 0 1 1 1 1
violated property: equal black height on every root-to-nil path
Deleting black leaf 10 without the delete fixup leaves the two sides with different black heights: 0 on the left path and 1 on the right. The tree is still a valid search tree and answers every lookup correctly, which is why only a property check catches the bug.
4. The Root Bug in Java
private void insertFixup(Node node) {
while (node.parent.red) {
if (node.parent == node.parent.parent.left) {
Node uncle = node.parent.parent.right;
if (uncle.red) {
node.parent.red = BLACK;
uncle.red = BLACK;
node.parent.parent.red = RED;
node = node.parent.parent;
} else {
if (node == node.parent.right) {
node = node.parent;
rotateLeft(node);
}
node.parent.red = BLACK;
node.parent.parent.red = RED;
rotateRight(node.parent.parent);
}
} else {
Node uncle = node.parent.parent.left;
if (uncle.red) {
node.parent.red = BLACK;
uncle.red = BLACK;
node.parent.parent.red = RED;
node = node.parent.parent;
} else {
if (node == node.parent.left) {
node = node.parent;
rotateRight(node);
}
node.parent.red = BLACK;
node.parent.parent.red = RED;
rotateLeft(node.parent.parent);
}
}
}
// BUG: root.red = BLACK is missing here.
}
Output:
RedRootAfterInsert: the insert fixup never forces the root black
insert 50, 30, 70, 10 -> root 50, root colour red, size 4
property walk: the root is red
The Java version of the root bug leaves 50 red at the root after inserting 50, 30, 70 and 10. The in-order sequence and every search are correct, so only a check that inspects colors finds it.
5. One Sibling Case Missing in Java
private void deleteFixup(Node node) {
if (node != root && !node.red) {
Node sibling = node == node.parent.left ? node.parent.right : node.parent.left;
if (!sibling.red && !sibling.left.red && !sibling.right.red) {
sibling.red = RED;
node = node.parent;
}
// BUG: the red-sibling and red-child sibling cases are missing.
}
node.red = BLACK;
}
Output:
DeleteSiblingMissing: the delete fixup handles only the black-sibling case
delete 10 from 6 keys -> root 20, height 3, size 5
property walk: black heights 1 and 2 are unequal
This delete fixup handles only the black-sibling case and ignores the red-sibling and red-nephew shapes. Deleting 10 from the six-key tree leaves black heights of 1 and 2 on two paths. A partial fixup can pass many deletions and fail only when the sibling is red, which is exactly the case a shallow test misses.
Key Takeaways
- A red-black tree is a BST with one color bit per node and five rules that keep the height within 2 log2(n + 1), without storing a height.
- Insertion runs a fixup while the parent is red: a red uncle means recolor, a black uncle means one or two rotations, and the root is forced black at the end.
- Deletion of a black node carries an extra black up through the sibling cases, with at most three rotations.
- On 100,000 sorted keys the red-black tree is 14 edges taller than AVL, 30 against 16, and both rotate about once per insertion.
- On 100,000 random keys both trees reach 19 edges, and red-black rotates 16 percent less.
- Java’s
TreeMapmakes exactly the same lookup comparisons as the article’s tree, andstd::mapfollows the same logarithmic profile with about two extra comparisons per lookup. - The five pitfalls keep a valid search order and break a color rule, so only a property check catches them.
Frequently Asked Questions
Conclusion
The red-black tree is the standard library’s balanced tree for a reason. Five color rules, two fixups and a few rotations buy a worst-case height of 2 log2(n + 1) and cheap updates. Against AVL on identical input, the tree is 14 edges taller on 100,000 sorted keys and rotates about as often, while on random keys both reach 19 edges and red-black needs 16 percent fewer rotations. The counting comparators show TreeMap making exactly the lookups of the article’s tree, and std::map following the same profile.
The data structures hub places the tree beside the BST and AVL tree. In production, use the standard ordered map and leave the colors to the library. Write the tree yourself when the invariant is the point, and keep the property check in the tests, because every pitfall above keeps a valid search order while it breaks a rule.
Source Code and Tests
The programs on this page are in the data-structures/red-black-tree directory of two MYCPLUS example repositories:
| Language | Repository directory | Build status |
|---|---|---|
| C++ | mycplus/cpp-examples: data-structures/red-black-tree | |
| Java | mycplus/java-examples: data-structures/red-black-tree |
The C++ example builds and tests with CMake:
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure
The Java example uses javac and java directly:
javac --release 17 -d build src/*.java tests/*.java pitfalls/*.java
java -ea -cp build TestRedBlackTree
java -cp build RedBlackTreeDemo
The demo’s output is compared byte for byte with tests/expected/ordered.txt. The tests insert, delete and search against a reference model, check all five properties and the black height after every batch, and cover duplicates and every deletion shape. The C++ workflow also runs the tests, demo, experiments and pitfalls under AddressSanitizer and UndefinedBehaviorSanitizer, checks every row of the height table, and checks each pitfall’s output line.
What I Verified
The example directories contain the test programs and the captured runs. The table states which system ran each check.
| Check | Ubuntu 24.04 (WSL2) | Windows 11 |
|---|---|---|
| Build and tests, C++, g++ 13.3, C++17 and C++20 | Pass (7 of 7 tests) | Not applicable |
| Build and tests, C++, clang++ 18.1.3, C++17 and C++20 | Pass (7 of 7 tests) | Not applicable |
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive- | Not applicable | Pass (7 of 7 tests, C++17 and C++20) |
| AddressSanitizer and UndefinedBehaviorSanitizer, C++ tests, demo and pitfalls | Pass (7 of 7 tests) | Not applicable |
| Java build and tests | Pass (44,540 checks on OpenJDK 21, output byte-identical to Windows) | Pass (44,540 checks on JDK 27, the captured output) |
| Five pitfalls, each caught by the property check named in its section | Pass (3 C++ and 2 Java) | Not applicable |
| Height and map experiments | C++ run, output above | Java run, output above |
| Independent rerun on a second Linux x86-64 machine (GCC 13.3, Clang 18.1.3, OpenJDK 21) | Pass (C++ 7 of 7 with both compilers, Java 44,540 checks, demo, both experiments and all five pitfalls byte-identical to the captures) | Not applicable |
Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, macOS, other JVMs, concurrent access, and inputs other than sorted and one fixed random order.




