Red-black trees, a lesson with exercises
How a red-black tree keeps a binary search tree balanced with one colour bit, why that bounds its height, how insertion and deletion repair it, how it compares with AVL trees and B-trees, where Linux, Java, nginx and VS Code use it, and four proofs and ten judge problems to practise on.
A binary search tree keeps keys in order: everything in a node’s left subtree is smaller, everything in its right subtree is larger. Search, insert, delete, “next key after x” and “smallest key” all cost one step per level, so they cost O(h) for a tree of height h. With keys arriving in random order, h stays around a small multiple of . With keys arriving sorted, each new key becomes the right child of the previous one, the tree is a linked list, and h = n. Inserting 1, 2, …, 200,000 into a plain BST takes about 20 billion comparisons.
A balanced tree fixes the height at O(log n) whatever the order. The red-black tree is the one most standard libraries picked: C++‘s std::map in libstdc++, Java’s TreeMap, and the Linux kernel’s generic rbtree. It stores one extra bit per node, a colour, and repairs itself after each change with a few recolourings and at most two or three rotations. There are companion lessons on B-trees, the wide trees that red-black trees turn out to encode, and on segment trees, for range queries over arrays.
five rules
The rules as stated in chapter 13 of CLRS1, the textbook Introduction to Algorithms by Cormen, Leiserson, Rivest and Stein, named after its authors’ initials:
- Every node is red or black.
- The root is black.
- Every leaf (the empty NIL child at the bottom) is black.
- A red node’s children are both black.
- For each node, every path from it down to a NIL leaf passes through the same number of black nodes.
That number in rule 5, counted from a node x down to the leaves and not counting x itself, is the black-height bh(x). Rules 4 and 5 together give the guarantee: every path has the same number of black nodes, and red nodes can’t sit next to each other, so the longest path from the root is at most twice the shortest.
the height bound
CLRS proves that a red-black tree with n keys has height at most 1. The proof is short and worth knowing by heart.
First, the subtree under any node x holds at least keys. By induction on height: a NIL leaf has bh = 0 and holds 0 keys. An internal node’s two children each have black-height at least bh(x) − 1 (exactly that if the child is black, bh(x) if it is red), so they hold at least keys each, and with x itself that’s .
Second, by rule 4 at least half of the nodes on any path from the root are black, so bh(root) ≥ h/2. Put together:
For a million keys that’s at most 40 levels, against a million for the sorted plain BST.
Search is the plain BST search and never looks at the colours. It compares against one node per level, so at most comparisons, O(log n), with O(1) extra memory. The colour costs one bit per node, often hidden in a spare bit of a pointer, so the tree takes O(n) memory like any BST.
a red-black tree is a 2-3-4 tree
The colours make more sense once you see where they come from. Rudolf Bayer described these trees in 1972 as “symmetric binary B-trees”, a way to store a B-tree of order 4 inside a binary tree2. Leo Guibas and Robert Sedgewick reworked them in 1978 as a two-colour framework for balanced trees, and the red and black names come from that paper3. Wikipedia gives two stories for the choice of red: the colour laser printer at Xerox PARC, or the pens the authors had to hand4.
A 2-3-4 tree is a search tree whose nodes hold one, two or three keys (and so have two, three or four children), with every leaf on the same level. It’s the smallest B-tree, with minimum degree 2. Lift each red node into its black parent and a red-black tree becomes one: a black node alone is a 2-node, a black node with one red child is a 3-node, a black node with two red children is a 4-node. Rule 4 stops a red node from having a red child, so no node gets more than three keys. Rule 5 says every leaf is the same number of black nodes down, so in the 2-3-4 tree every leaf is on the same level. Sedgewick: “All red-black trees are based on implementing 2-3 or 2-3-4 trees within a binary tree, using red links to bind together internal nodes into 3-nodes or 4-nodes”5.
A red-black tree of twelve keys built by inserting 13, 8, 17, 1, 11, 15, 25, 6, 22, 27, 20 and 3. The root 13 is black. Its children 8 and 17 are black. Under 8 sit black 3 (with red children 1 and 6) and black 11. Under 17 sit black 15 and red 25, whose children are black 22 (with red child 20) and black 27. Every path from the root down passes three black nodes. Switching to the 2-3-4 view lifts each red node onto its parent's row: the tree becomes three levels, with nodes {13}, then {8} and {17, 25}, then {1, 3, 6}, {11}, {15}, {20, 22} and {27}, and every leaf on the last level.
Every red-black operation is a 2-3-4 operation in disguise. A new key is inserted red, which in 2-3-4 terms means added to an existing node. When that node already had three keys, it overflows, and a 2-3-4 tree splits it and pushes the middle key up to the parent. In the red-black tree that split is a colour flip5. Drawing the 2-3-4 picture next to the red-black one is the easiest way to work out an insertion case.
rotations
The repairs need one structural operation besides recolouring. A rotation turns a parent-child pair upside down while keeping the in-order sequence of keys.
Node x has left subtree alpha and right child y; y has subtrees beta and gamma. A left rotation at x moves y up into x's place, makes x y's left child, and moves beta from y's left to x's right. The order alpha, x, beta, y, gamma is the same before and after. A right rotation at y undoes it.
struct Node { int key; bool red; Node *l, *r, *p; };
void rotate_left(Node*& root, Node* x) {
Node* y = x->r;
x->r = y->l; // β moves from y to x
if (y->l) y->l->p = x;
y->p = x->p; // y takes x's place
if (!x->p) root = y;
else if (x == x->p->l) x->p->l = y;
else x->p->r = y;
y->l = x; // x goes under y
x->p = y;
}
// rotate_right is the mirror image: swap every l and r
A rotation is O(1): it moves three parent-child links (six pointer writes, counting the parent pointers) and never breaks the search order. Insertion uses at most two of them and deletion at most three.
insertion
Insert the key as in a plain BST and colour it red. Red keeps rule 5 intact (no path gains a black node). The only rule that can break is rule 4, when the new node’s parent is red too. The fix-up walks up from the new node z while z and its parent are both red. With p the parent, g the grandparent (black, since p is red) and u the uncle (g’s other child), there are three cases1:
- The uncle is red. Make p and u black and g red, then continue from g, two levels up. In 2-3-4 terms, z’s node had three keys (g with red p and u) and overflowed: this is the split, with g pushed up into its own parent. It’s the only case that loops.
- The uncle is black and z is an inner child (z is a right child of a left child, or the mirror). Rotate at p so that z and p swap roles. This turns it into the next case.
- The uncle is black and z is an outer child. Make p black and g red, rotate at g. p is now the black top of a node holding z and g as red children, a valid 4-node. The loop ends.
Finally colour the root black. In code, with null children counting as black:
bool is_red(Node* n) { return n && n->red; }
void insert_fixup(Node*& root, Node* z) {
while (is_red(z->p)) {
Node *p = z->p, *g = p->p;
bool left = (p == g->l);
Node* u = left ? g->r : g->l;
if (is_red(u)) { // split: push the red up
p->red = u->red = false; g->red = true;
z = g;
continue;
}
if (z == (left ? p->r : p->l)) { // inner child: straighten
z = p;
left ? rotate_left(root, z) : rotate_right(root, z);
}
z->p->red = false; g->red = true; // outer child: rotate g
left ? rotate_right(root, g) : rotate_left(root, g);
}
root->red = false;
}
The tree after inserting the keys 1, 2, 3 and so on in order, with the fix-up steps of the last insertion listed below it. After 8 keys the tree has height 4 (the bound 2·log2(9) is 6.3, a plain BST would have height 8). Inserting 8 went: uncle 5 is red, recolor 7, 5 and 6 and move up to 6; then rotate left at 2, recolor 4 black and 2 red. With 15 sorted keys the height is 6. A second mode inserts the keys 1 to 15 in a fixed random order (5, 14, 10, 13, 12, 2, 9, 4, 7, 6, 1, 8, 3, 15, 11) and ends with height 5.
An insertion takes O(log n) time in the worst case. The walk down to the new leaf is O(log n), by the height bound. The fix-up can climb O(log n) levels through the red-uncle case, recolouring three nodes each time, but each rotation case ends it, so an insertion does at most two rotations. Over a sequence of operations the recolouring is O(1) amortized, a result of Tarjan’s67. The fix-up needs O(1) extra memory, since it follows parent pointers instead of a stack. Rotations are the expensive part in practice (they move pointers that other code may be holding, and in augmented trees they force recomputation), so a constant bound on them matters.
Watch the sorted sequence in fig 3, the input that turns a plain BST into a list. Every insertion lands at the right end and the outer-child case keeps firing on the right spine. 15 keys take 6 levels, against 15 for the plain BST and 4 for a perfectly balanced tree.
deletion
Deletion is where most people give up on implementing red-black trees, and the cases are longer, but the idea is the same. Delete as in a BST (a node with two children swaps its key with its successor first, so the node that gets removed has at most one child). If the removed node was red, nothing breaks. If it was black, every path through it lost one black node, and the fix-up pushes an “extra black” up the tree until it can be absorbed. With x the node carrying the extra black and w its sibling, CLRS has four cases1:
- w is red: rotate at the parent and recolour, which gives x a black sibling and moves to one of the cases below.
- w is black with two black children: make w red and move the extra black up to the parent. This is a merge of two 2-3-4 nodes and the only case that loops. It does no rotations.
- w is black, its near child red and far child black: rotate at w, which moves to case 4.
- w is black with a red far child: rotate at the parent, recolour, done.
Five deletions from a red-black tree built from the keys 45, 40, 20, 30, 25, 5, 60, 15, 50, 55, 10 and 35. Deleting 30 removes a black node whose red child takes its place and turns black. Deleting 25, which has two children, moves its successor into its place; the removed node was black and left a nil with an extra black, which goes through case 1 (red sibling, rotate), then case 2 (black sibling with black children, push the extra black up) to a red node that turns black. Deleting 45 runs case 3 and then case 4. Deleting 60 runs case 2 up to the root. Deleting 50 removes a red leaf, which needs no fix.
A deletion takes O(log n) time in the worst case. Finding the key and its successor is one walk down, O(log n). In the fix-up, case 2 can climb one level at a time up to the root, O(log n) recolourings. Cases 1, 3 and 4 end the loop after a constant number of steps (case 1 leads to case 2 with a red parent, which stops, or to case 3 or 4), so a deletion does at most three rotations18. Like insertion, it needs O(1) extra memory. Exercise P2 below walks through a full sequence by hand.
measured
Heights measured by inserting n keys into the red-black tree above, for n from 2 to 16,384. With sorted keys the height grows to 26 at 16,384 keys, close to the bound 2·log2(n+1) = 28, with 1.00 rotations per insertion. With the same keys in random order the height is 17, against log2(n+1) = 14 for a perfectly balanced tree, with 0.59 rotations per insertion.
Sorted input gave the taller tree and stayed under the bound. It’s also the case where the tree rotates on almost every insertion; random input rotates on about three insertions in five.
next to the alternatives
| structure | height (worst) | rotations per insert / delete | guarantee |
|---|---|---|---|
| plain BST | n | 0 / 0 | none |
| AVL tree | ≤ 2 / O(log n) | worst case | |
| red-black tree | ≤ 2 / ≤ 3 | worst case | |
| WAVL tree | ≤ AVL with insertions only, ≤ red-black otherwise | ≤ 2 / ≤ 2 | worst case |
| treap, skip list | O(log n) expected | O(1) expected | randomised |
| B-tree | splits and merges | worst case |
The AVL and WAVL rows come from Haeupler, Sen and Tarjan7. AVL trees are more tightly balanced, so lookups touch fewer nodes, and they pay for it with more rebalancing work on deletion. Ben Pfaff benchmarked 20 BST variants on traces from real system software in 2004 and found AVL trees faster than red-black trees by up to 20% on those traces, red-black trees doing 12% to 32% more comparisons. His advice: red-black trees for random input with occasional sorted runs, AVL when insertions are mostly sorted and followed by random lookups, and splay trees when accesses cluster9.
On modern hardware the bigger cost is memory. Every key in a binary tree is its own heap allocation, and every comparison can be a cache miss. Abseil’s B-tree notes put libstdc++‘s std::set<int32_t> at 40 bytes per value against 4.3 to 5.1 bytes for absl::btree_set. The price is pointer stability: a B-tree moves values around inside its nodes when it splits, so pointers and iterators into it don’t survive inserts10. Rust’s standard library chose a B-tree for BTreeMap for the same reason (the B-tree lesson covers both)11. The Linux rbtree is built the other way: the node is embedded inside the caller’s own struct, and code keeps pointers to those structs across inserts8.
what you can improve
Fewer cases. Sedgewick’s left-leaning red-black tree (2008) only allows red links that lean left. That gives a one-to-one match with 2-3 trees and cuts the code to “less than one-fourth” of the usual size5. The cost is rotations: a left-leaning tree can need Ω(log n) of them per update, where the classic tree needs at most three7.
Fewer rotations. Haeupler, Sen and Tarjan’s weak AVL (WAVL) trees do at most two rotations on both insertion and deletion. With insertions only, a WAVL tree is an AVL tree; with deletions mixed in, its height is never worse than a red-black tree’s7.
Smaller nodes. Linux keeps the colour in the lowest bit of the parent pointer, since nodes are aligned and that bit is always 0. A node is three words: parent-and-colour, right and left12.
Constant-time minimum. Linux’s rb_root_cached keeps a pointer to the leftmost node, so “smallest key” is one load instead of a walk down. libstdc++‘s header node keeps both the leftmost and the rightmost, so begin() and rbegin() are O(1)813.
Augmentation. Store in each node something computed from its subtree, such as the subtree size or the largest interval end, and keep it right during rotations, which only touch two nodes. Subtree sizes give an order-statistic tree: the k-th smallest key, and the rank of a key, in O(log n). The largest end gives an interval tree. CLRS covers both (chapter 14 in the third edition)1, and Linux has generic support for augmented trees8. In C++ contests, GNU’s policy-based tree with tree_order_statistics_node_update is an augmented red-black tree you can use directly14.
Persistence. Chris Okasaki’s functional insertion reduces the three cases to one balance function with four patterns, which makes an immutable red-black tree a short program15. Deletion in that setting took longer to get right. Kahrs’ version is the one Scala’s collections use16.
case studies
The Linux scheduler. The Completely Fair Scheduler (CFS) kept every runnable task in a red-black tree keyed by its virtual runtime, the CPU time it has used, scaled by its priority. Picking the next task meant taking the leftmost node, the one that had run least17, and the cached leftmost pointer made that O(1). Since kernel 6.6 the scheduler is EEVDF18, and it uses an augmented red-black tree. In current kernels the tree is ordered by each task’s virtual deadline and every node also stores the minimum virtual runtime in its subtree. A comment in kernel/sched/fair.c explains that this lets the tree “also function as a heap based on the vruntime”, so the scheduler can skip whole subtrees of tasks that aren’t eligible yet and find the eligible task with the earliest deadline in O(log n)19.
epoll and timers. Each epoll instance keeps the file descriptors it watches in a red-black tree keyed by the (file, fd) pair, so epoll_ctl can find, add and remove a watch in O(log n) among thousands20. The kernel’s high-resolution timers sit in a timerqueue, a red-black tree ordered by expiry time with a cached leftmost node, so the next timer to fire is always one load away21. nginx does the same for its event loop: timers in a red-black tree keyed by absolute expiry in milliseconds, with the minimum giving how long the next wait can be. It also skips the delete-and-reinsert when a timer would move by less than 300 ms, “to minimize the rbtree operations for fast connections”22.
Java. TreeMap is a red-black tree with guaranteed log(n) get, put and remove, adapted from CLRS23. Since JDK 8, HashMap uses them too: when one bucket collects 8 entries (and the table has at least 64 buckets), its linked list turns into a red-black tree, so a flood of colliding keys costs O(log n) per lookup in that bucket instead of O(n)2425. The source comment notes that with a good hash function a bucket of 8 has a probability of about 0.0000000625, so the tree exists for adversarial or broken hash codes.
C++. In libstdc++, std::map, std::set, std::multimap and std::multiset are all one _Rb_tree class, “based on those in Cormen, Leiserson, and Rivest”13.
VS Code. In 2018 VS Code replaced its array of lines with a piece table stored in a red-black tree. Each node points at a piece of a text buffer and stores the length and line-break count of its left subtree, so finding the text at an offset or a line number is a walk down the tree. The old model used about 600 MB for a 35 MB file with 13.7 million lines; the new one stays close to the file size. The team’s reason for the red-black tree: it is “more ‘editing’ friendly”26.
Where it was replaced. Linux used a red-black tree (plus a linked list) for the virtual memory areas of each process until 6.1, when the maple tree, a B-tree variant built for ranges and lockless reads, took over2728. The B-tree lesson has the maple tree’s side of the story. Redis never used one: its sorted sets were skip lists, which antirez chose because they are simpler to implement and debug and walk ranges well29. Redis’s development branch now stores large sorted sets in a packed B+ tree30.
exercises
Proofs first, then problems where an ordered set is the intended tool. For those you can use std::set or TreeMap; the last one asks you to write the tree yourself.
P1Which trees are valid?●○○ by hand
Write a function that checks all five rules in O(n) and returns the black-height, or reports the first violation. Then insert 36 into the tree of fig 1 by hand: what colour does it get, and does anything change?
hint
Compute the black-height bottom-up and compare left and right at each node. Rule 4 is a check between a node and its children.
solution sketch
check(n): return 1 for null; if n is red and a child is red, fail; recurse on both children; if the two black-heights differ, fail; return that height plus 1 if n is black. Also check the root is black and the BST order. For 36: it goes right of 27 as a red leaf, its parent 27 is black, so nothing else happens.
P2A full insert and delete sequence●●○ by hand
From CLRS (exercises 13.3-2 and 13.4-3): insert 41, 38, 31, 12, 19, 8 into an empty tree, then delete 8, 12, 19, 31, 38, 41. Draw the tree after each step and name the case used.
hint
Draw the 2-3-4 tree next to it. Each split is a red-uncle recolouring; each merge in deletion is case 2.
solution sketch
Inserting 31 triggers the outer-child case (rotate at 41); 12 is a red-uncle recolour; 19 is an inner child followed by the outer-child rotation; 8 is a red-uncle recolour. You can check every insertion step with fig 3’s code. For the deletions, check each intermediate tree with your P1 validator.
P3Prove the bounds●●○ proof
(a) Prove that the longest root-to-leaf path is at most twice the shortest. (b) For black-height k, what are the fewest and the most keys a red-black tree can hold? (CLRS 13.1-5 and 13.1-6.)
hint
For (b), the fewest is when every node is black; the most is when black and red levels alternate.
solution sketch
(a) Every path has bh black nodes, and at most one red node per black node, so lengths are between bh and 2·bh. (b) Fewest: a complete all-black tree, keys. Most: alternate black and red levels for 2k levels, keys.
P4Count the rotations●●● proof
Show that an insertion does at most 2 rotations and a deletion at most 3. Then explain why sorted insertion in fig 5 does about one rotation per key in the long run.
hint
Which cases end the loop? For the second part, look at the logs in fig 3 for sorted input: count rotations over keys 8 to 15.
solution sketch
Only the red-uncle case (insertion) and case 2 (deletion) loop, and neither rotates. Every other case leads to termination after at most 2 rotations (inner, then outer) or 3 (cases 1, 3 and 4). For sorted keys, the log in fig 3 shows the pattern: an odd key lands as the outer child of a red parent at the bottom of the right spine and does one rotation; an even key splits a 4-node, pushes a key up the spine, and the push ends in one rotation higher up. Counting with the figure’s code, 16,358 of 16,384 sorted insertions do exactly one rotation and 26 do none.
EX 1Concert Tickets●○○ CSES 1091
cses.fi/problemset/task/1091. n tickets with prices. Customers arrive in order, each with a maximum price, and buys the most expensive remaining ticket they can afford (or prints −1). n, m ≤ 2·10^5.
hint
You need “largest price ≤ t” and removal, with duplicates.
solution sketch
A multiset. For each customer, it = upper_bound(t); if it’s begin(), print −1, else step back, print and erase that one element. O((n + m) log n).
EX 2My Calendar I●○○ LeetCode 729
leetcode.com/problems/my-calendar-i. Accept a booking [start, end) only if it overlaps no accepted booking.
hint
Only two existing bookings can overlap the new one: the last one starting before it and the first one starting at or after it.
solution sketch
A map from start to end. Check the first booking with start ≥ new start (it must start at or after the new end) and the one before it (it must end at or before the new start). O(log n) per booking.
EX 3Traffic Lights●●○ CSES 1163
cses.fi/problemset/task/1163. A street of length x. Lights are added one by one; after each, print the longest stretch without a light.
hint
Two ordered structures: one of positions, one of gap lengths.
solution sketch
A set of positions starting with {0, x} and a multiset of gaps starting with {x}. For a new light p, find its neighbours a < p < b, erase one copy of b − a, insert p − a and b − p, and print the multiset’s largest element. O(n log n).
EX 4Room Allocation●●○ CSES 1164
cses.fi/problemset/task/1164. Customers with arrival and departure days; give each a room so that nobody shares a room on a day, using as few rooms as possible, and print the assignment.
hint
Process customers by arrival. Which room should a new customer take?
solution sketch
Keep a set of (departure day, room) for occupied rooms. For each arrival, if the earliest departure is before the arrival day, reuse that room; otherwise open a new one. O(n log n). A priority queue works too; a set also lets you print the assignment easily.
EX 5Contains Duplicate III●●○ LeetCode 220
leetcode.com/problems/contains-duplicate-iii. Are there i ≠ j with |i − j| ≤ indexDiff and |a[i] − a[j]| ≤ valueDiff?
hint
Slide a window of the last indexDiff values and ask the window for its smallest value ≥ a[i] − valueDiff.
solution sketch
A set holding the window. For each i, lower_bound(a[i] − valueDiff); if it exists and is ≤ a[i] + valueDiff, answer true. Insert a[i], erase a[i − indexDiff]. O(n log k). Buckets of width valueDiff + 1 give an O(n) solution as a follow-up.
EX 6Sliding Window Median●●○ CSES 1076
cses.fi/problemset/task/1076. Print the median of every window of k consecutive numbers.
hint
Two multisets, a low half and a high half, kept balanced in size.
solution sketch
Low holds the smaller ⌈k/2⌉ values, high the rest; the median is low’s largest. Insert into the right half, erase the outgoing value from whichever half holds it, then move one element across if the sizes are off. O(n log k). An order-statistic tree answers “k/2-th smallest” directly.
EX 7Josephus Problem II●●○ CSES 2163
cses.fi/problemset/task/2163. n children in a circle; repeatedly skip k and remove the next one. Print the removal order. n ≤ 2·10^5, k up to 10^9.
hint
If you know the current position as an index among the remaining children, the next one is a modular jump. You need “the i-th remaining child”.
solution sketch
An order-statistic tree (or GNU tree with find_by_order). Position = (position + k) mod size, print and erase the element at that index, and the position now points at the next child. O(n log n). The count segment tree from the segment tree post’s EX 7 works too.
EX 8Salary Queries●●○ CSES 1144
cses.fi/problemset/task/1144. Salaries change; count employees whose salary is in [a, b]. Salaries up to 10^9.
hint
Count in [a, b] = rank of b + 1 minus rank of a, where rank(x) is the number of salaries below x.
solution sketch
An order-statistic multiset of (salary, id) pairs, with order_of_key giving ranks. O((n + q) log n). Offline: compress all salaries and use a Fenwick tree.
EX 9Count of Smaller Numbers After Self●●● LeetCode 315
leetcode.com/problems/count-of-smaller-numbers-after-self. For each i, how many later elements are smaller than a[i]?
hint
Walk from the right and keep everything you’ve seen in a structure that answers “how many are below x”.
solution sketch
Insert from right to left into an order-statistic tree and record the rank of a[i] before inserting it. Use (value, index) pairs so duplicates are counted correctly. O(n log n). Merge sort counting inversions or a Fenwick tree over compressed values also work.
EX 10Order statistic set, by hand●●● SPOJ ORDERSET
spoj.com/problems/ORDERSET. Operations: insert x, delete x, the k-th smallest element, and how many elements are below x. Write the red-black tree yourself this time.
hint
Add a size field to each node. Which nodes’ sizes change during a rotation?
solution sketch
Start from this post’s insert code. Keep size(n) = size(l) + size(r) + 1. During a rotation only x and y change; recompute x first (it’s now lower), then y. Insertion adds 1 along the search path; deletion subtracts 1 along the path to the removed node. k-th: compare k with size(left) + 1 and go left, stop or go right with k reduced. Rank: sum size(left) + 1 every time the search goes right. O(log n) each. This is CLRS’s OS-SELECT and OS-RANK.
The CSES “Sorting and Searching” section has more problems where std::set or std::multiset is the intended tool, and Sedgewick’s left-leaning paper is the shortest correct implementation to read after CLRS5.
My recommendation: learn the insertion cases through the 2-3-4 picture, write insertion and the P1 validator once, and use the library’s tree for everything else. For deletion I’d read the Linux implementation, which has the CLRS case numbers in its comments12.
sources
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 3rd ed., chapter 13, red-black trees (excerpt)
- Bayer, symmetric binary B-trees: data structure and maintenance algorithms, Acta Informatica 1 (1972)
- Guibas and Sedgewick, a dichromatic framework for balanced trees, FOCS 1978
- Wikipedia, red-black tree (read 12 November 2026)
- Sedgewick, left-leaning red-black trees (2008)
- Tarjan, updating a balanced search tree in O(1) rotations, Information Processing Letters 16 (1983)
- Haeupler, Sen and Tarjan, rank-balanced trees (preprint of ACM Transactions on Algorithms 11(4), 2015)
- Linux kernel documentation, red-black trees (rbtree) in Linux (read 12 November 2026)
- Pfaff, performance analysis of BSTs in system software, SIGMETRICS 2004
- Abseil, B-tree containers design note (read 12 November 2026)
- Rust standard library, BTreeMap documentation (read 12 November 2026)
- Linux source, lib/rbtree.c and include/linux/rbtree_augmented.h (read 12 November 2026)
- GCC libstdc++ source, bits/stl_tree.h (read 12 November 2026)
- GCC libstdc++ manual, policy-based data structures (read 12 November 2026)
- Okasaki, red-black trees in a functional setting, Journal of Functional Programming 9(4) (1999)
- Germane and Might, deletion: the curse of the red-black tree, Journal of Functional Programming 24(4) (2014)
- Linux kernel documentation, CFS scheduler (read 12 November 2026)
- Linux kernel documentation, EEVDF scheduler (read 12 November 2026)
- Linux source, kernel/sched/fair.c (read 12 November 2026)
- Linux source, fs/eventpoll.c (read 12 November 2026)
- Linux source, include/linux/timerqueue.h (read 12 November 2026)
- nginx source, src/event/ngx_event_timer.h and ngx_event_timer.c (read 12 November 2026)
- Java SE 21 API, TreeMap (read 12 November 2026)
- OpenJDK, JEP 180: handle frequent HashMap collisions with balanced trees
- OpenJDK source, java/util/HashMap.java (read 12 November 2026)
- Lyu, text buffer reimplementation, VS Code blog (23 March 2018)
- LWN, introducing maple trees (12 February 2021)
- LWN, the 6.1 merge window, part 1 (2022)
- antirez on why Redis sorted sets use skip lists, Hacker News
- Redis source, src/t_zset.c on the unstable branch (read 12 November 2026)