Red-black tree visualizer

A red-black tree is a binary search tree that keeps itself balanced using one bit per node: red or black. Insert and delete keys below and step through every recolour and rotation, with the five rules checked after each operation. Further down: the rules, the insertion and deletion cases, worked examples, and red-black versus AVL.

Keys
6
Height
4
Black nodes per path
3
Rotations
0
Quick
Steps of the last operation
The tree
81219313841

black node red node changed in this step

The five rules, checked now
  • 1. Every node is red or black.
  • 2. The root is black.
  • 3. Every NIL leaf is black.
  • 4. A red node has no red child.
  • 5. Every path from a node to its NIL leaves has the same number of black nodes (here 3, counting the root and the NIL leaf).

Height 4; the guarantee for 6 keys is at most 5.61 (2 log₂(n + 1)).

How to use the simulator

Type a key and press Insert or Delete. The tree updates, and the panel lists every step the algorithm took: where the key went, each recolouring, each rotation. Press Previous and Next, or click a step, to see the tree at that moment, with the nodes involved outlined. The five red-black rules are checked after every operation.

  • Press Insert 1 to 10 in order. A plain binary search tree would become a chain ten nodes long; this one stays 5 levels deep.
  • Insert 5 into the starting tree: a case 3 rotation. Then insert 4: a case 1 recolouring pushes the problem two levels up, where a case 3 rotation fixes it.
  • Delete the root and follow the deletion fix-up, the harder half of the algorithm.
  • Turn on Show NIL leaves to see the empty black leaves that the rules count.

The code follows the insertion and deletion procedures in Introduction to Algorithms by Cormen, Leiserson, Rivest and Stein. It was checked by 80,000 random insertions and deletions against a sorted set, verifying the five rules and the key order after every one.

What is a red-black tree?

A red-black tree is a binary search tree in which every node also stores a colour, red or black, and the colours must follow a few rules. A binary search tree keeps smaller keys to the left and larger keys to the right, so finding a key takes as many steps as the tree is tall. An ordinary one can grow lopsided: inserting keys in sorted order produces a chain, and lookups become as slow as scanning a list. The red-black rules prevent that. After every insertion or deletion, the tree repairs any broken rule by recolouring nodes and performing a few rotations, which keeps its height logarithmic in the number of keys.

Red-black trees are the most common balanced search tree in standard libraries, because they guarantee O(log n) for every operation while doing little restructuring on updates.

The five red-black tree properties

  1. Every node is either red or black.
  2. The root is black.
  3. Every leaf is black. In this formulation the leaves are the empty NIL children, not nodes holding keys.
  4. If a node is red, both its children are black. So two red nodes are never adjacent on a path.
  5. For every node, all paths from it down to its NIL leaves contain the same number of black nodes. This number is the node's black height.

Some texts drop rule 3 and count black heights without the NIL leaves, or allow a red root; these are differences of bookkeeping, not of the structure.

Why the height stays small

Rule 5 means every path from the root to a leaf has the same number of black nodes, say b. Rule 4 means red nodes cannot sit next to each other, so a path has at most one red node for each black one, and its length is between b and 2b. The shortest path is therefore at least half as long as the longest.

A subtree whose root has black height b contains at least 2b − 1 keys (it contains a complete binary tree of black nodes). Putting the two facts together, a red-black tree with n keys has height at most 2 log₂(n + 1). Inserting 1 to 15 in order, the worst case for a plain binary search tree, gives this tree a height of 6, against a bound of 8:

123456789101112131415

Rotations

A rotation changes the shape of a binary search tree without changing the order of its keys. A left rotation at node x moves its right child y up into x's place, makes x the left child of y, and hands y's old left subtree to x as its new right subtree. A right rotation is the mirror image. Each takes constant time, since only three links change. Rotations, together with recolouring, are all a red-black tree uses to rebalance.

Red-black tree insertion

Insert the new key as in a plain binary search tree, as a leaf, and colour it red. A red node adds nothing to any path's black count, so rule 5 still holds. The only rule that can break is rule 4, if the new node's parent is also red (or rule 2, if the new node is the root). The fix depends on the new node's uncle, its parent's sibling:

  • Case 1, the uncle is red. Colour the parent and the uncle black and the grandparent red. Black counts are unchanged below the grandparent, but the grandparent may now be a red node with a red parent, so repeat the check two levels up.
  • Case 2, the uncle is black and the new node is an inner child (a right child of a left child, or the reverse). Rotate at the parent so the two red nodes form a straight line, which turns the situation into case 3.
  • Case 3, the uncle is black and the new node is an outer child. Colour the parent black and the grandparent red, then rotate at the grandparent. The parent takes the grandparent's place, black, with two red children, and the fix-up ends.

Finally colour the root black. Case 1 can repeat up the tree, but it only recolours, and cases 2 and 3 run at most once, so an insertion performs at most two rotations.

Red-black tree insertion example

Inserting 10, 20, 30, 15, 25, 5, 1 into an empty tree, as the simulator does it:

InsertWhat happens
10The tree is empty: 10 becomes the root, coloured red for now. The root 10 is red; colour it black. This adds one to every path's black count equally.
20Search for 20: 10. Insert it as a red leaf under 10.
30Search for 30: 10 → 20. Insert it as a red leaf under 20. Case 3: red 30 and red parent 20 are in a line with the grandparent. Colour 20 black and 10 red, then rotate at 10. Rotate left at 10: 20 moves up and 10 becomes its left child.
15Search for 15: 20 → 10. Insert it as a red leaf under 10. Red 15 has a red parent 10, and its uncle 30 is red too. Case 1, recolour: 10 and 30 turn black, grandparent 20 turns red. Continue from 20. The root 20 is red; colour it black. This adds one to every path's black count equally.
25Search for 25: 20 → 30. Insert it as a red leaf under 30.
5Search for 5: 20 → 10. Insert it as a red leaf under 10.
1Search for 1: 20 → 10 → 5. Insert it as a red leaf under 5. Red 1 has a red parent 5, and its uncle 15 is red too. Case 1, recolour: 5 and 15 turn black, grandparent 10 turns red. Continue from 10.

The resulting tree:

151015202530

Red-black tree deletion

Deletion starts like deletion in a plain binary search tree: a node with at most one child is replaced by that child; a node with two children is replaced by its successor, the smallest key in its right subtree. If the node that disappeared from its position was red, nothing else is needed. If it was black, every path through that spot is now one black node short, which breaks rule 5. The fix-up treats the node that took its place, x, as carrying an extra black, and looks at x's sibling w:

  • Case 1, the sibling is red. Recolour and rotate at the parent so that the sibling becomes black, then continue with one of the other cases.
  • Case 2, the sibling and both its children are black. Colour the sibling red, which removes a black from its side too, and move the extra black up to the parent.
  • Case 3, the sibling is black, its near child red and its far child black. Swap colours and rotate at the sibling, turning this into case 4.
  • Case 4, the sibling is black and its far child red. Recolour and rotate at the parent. The extra black is absorbed, and the fix-up ends.

If x is red, or reaches the root, colouring it black finishes the job. Deletion performs at most three rotations. Here is the simulator deleting 10 from the tree built above:

StepWhat happens
110 has two children. Its successor 15, the smallest key in its right subtree, takes its place and its colour.
2A black node was removed from one path, so that path is one black short. Fix it.
3Case 4: sibling 5 is black with a red far child 1. 5 takes the parent's colour, 15 and 1 turn black, and a rotation at 15 gives the NIL leaf's side its missing black node.
4Rotate right at 15: 5 moves up and 15 becomes its right child.
1515202530

Time complexity

OperationAverageWorst caseRestructuring
SearchO(log n)O(log n)None
InsertO(log n)O(log n)At most 2 rotations; amortised O(1) recolourings
DeleteO(log n)O(log n)At most 3 rotations
Minimum, maximum, successorO(log n)O(log n)None
In-order traversalO(n)O(n)None

Space is O(n): each node holds a key, two or three pointers, and one colour bit, which implementations often hide in an unused bit of a pointer.

Red-black tree vs AVL tree

AspectRed-black treeAVL tree
Balance ruleColour rules; longest path ≤ 2 × shortestSubtree heights differ by at most 1
Maximum height2 log₂(n + 1)About 1.44 log₂(n + 2)
LookupsSlightly deeper on averageSlightly shallower
Rotations per insertAt most 2At most 2
Rotations per deleteAt most 3Up to O(log n)
Extra data per node1 bitA balance factor or height
Typical useGeneral-purpose ordered maps with many updatesRead-heavy indexes

In practice the difference in lookup speed is small, and both are often beaten by B-trees when data lives on disk or when cache behaviour matters, because a B-tree node holds many keys. The AVL tree simulator shows the other side.

2-3-4 trees and left-leaning red-black trees

A red-black tree is a binary encoding of a 2-3-4 tree, a B-tree in which each node holds one, two or three keys. Take a black node together with its red children, and you have one 2-3-4 node: a black node alone holds one key, with one red child two keys, with two red children three keys. Rule 5 says every 2-3-4 leaf is at the same depth, as in any B-tree, and case 1 of insertion, recolouring a black node with two red children, is exactly splitting a full 2-3-4 node.

In 2008 Robert Sedgewick published the left-leaning red-black tree, which allows red links only on the left. That removes most of the symmetric cases and makes the code much shorter, at the price of a few more rotations. It corresponds to a 2-3 tree when 4-nodes are split on the way down.

Where red-black trees are used

  • C++ standard library implementations (libstdc++, libc++ and Microsoft's) use red-black trees for std::map, std::set and their multi- variants.
  • Java's TreeMap and TreeSet are red-black trees, and since Java 8 a HashMap bucket that collects eight or more entries is converted into a small red-black tree.
  • .NET's SortedSet<T> and SortedDictionary are built on a red-black tree.
  • The Linux kernel has a shared red-black tree library, lib/rbtree.c, used by the process scheduler to order runnable tasks, by epoll, by timers and by many file systems.

History

Rudolf Bayer described the structure in 1972 as the symmetric binary B-tree, a binary form of the B-trees he had invented. In 1978 Leonidas Guibas and Robert Sedgewick recast it with red and black colours in "A Dichromatic Framework for Balanced Trees". Sedgewick has said the colours were chosen partly because red looked best on the colour laser printer available to them at Xerox PARC. Introduction to Algorithms (first edition 1990) made the five-property formulation and its insertion and deletion cases the standard way the structure is taught.

Red-black tree questions and answers

What is a red-black tree?

A red-black tree is a self-balancing binary search tree. Each node is coloured red or black, and rules about the colours keep the longest path from the root to a leaf at most twice as long as the shortest. That keeps search, insertion and deletion at O(log n) time in the worst case.

What are the properties of a red-black tree?

Every node is red or black; the root is black; every leaf (NIL) is black; a red node has only black children, so no two reds are adjacent on a path; and every path from a node down to its NIL leaves passes through the same number of black nodes, called the black height.

What is the height of a red-black tree?

A red-black tree with n keys has height at most 2 log2(n + 1). The black-height rule makes every path contain the same number of black nodes, and the no-red-red rule means at most every other node on a path is red, so no path is more than twice as long as any other.

How does insertion work in a red-black tree?

Insert the key as in an ordinary binary search tree and colour it red. If its parent is also red, fix the violation: if the uncle is red, recolour the parent and uncle black and the grandparent red, and repeat from the grandparent; if the uncle is black, rotate (once or twice) and recolour so the red pair is resolved. Finally colour the root black. At most two rotations are needed.

What is the difference between an AVL tree and a red-black tree?

Both are balanced binary search trees with O(log n) operations. AVL trees are more strictly balanced (height at most about 1.44 log2 n), so lookups touch slightly fewer nodes; red-black trees allow more imbalance (height at most 2 log2(n + 1)) but need fewer rotations, at most two on insert and three on delete. Libraries that do many updates, such as std::map and Java’s TreeMap, usually choose red-black trees.

Why are new nodes inserted red?

Adding a red node never changes the number of black nodes on any path, so the black-height rule still holds. The only rule it can break is "no red node has a red child", which is local and fixed with recolouring and at most two rotations. Inserting a black node would unbalance black heights across the whole tree.

Where are red-black trees used?

In C++ standard library implementations of std::map and std::set, in Java’s TreeMap and TreeSet, in .NET’s SortedSet, inside Java 8’s HashMap for buckets with many collisions, and in the Linux kernel, whose rbtree library is used by the process scheduler, epoll and many other subsystems.

How are red-black trees related to 2-3-4 trees?

Every red-black tree corresponds to a 2-3-4 tree, a B-tree of order 4: a black node together with its red children forms one 2-3-4 node holding one, two or three keys. Recolouring corresponds to splitting a full node, which is why red-black insertion looks the way it does.

Further reading

Published Updated