A Red-Black tree is a binary search tree (BST) that takes some action to try and keep itself balanced. We know that BSTs are great at storing nodes identified by some key for which an order relationship exists (e.g., integers). They have the property that the values in the left sub-tree of each node *n* have keys smaller-than *n*‘s key `n.k`

, and those in the right sub-tree have keys greater-than `n.k`

^{1}.

In a BST, searching for a key takes logarithmic time, if the tree is balanced, that is, if the root’s left and right sub-tree have roughly the same height. The problem is that for particular key insertion orders, this might no longer be true: in particular, if you insert the keys in sorted order, you’ll find a tree which looks more like a linked list, that makes search linear in the worst case. This is why people have come up with a number of strategies to keep the BST balanced.

## Rotations

A RB tree changes the `Insert`

and `DeleteNode`

operations by adding a bunch of invariants, to satisfy which some additional work is needed when changing the number of nodes in the tree. The basic operation is the node rotation: there is a way of rotating the position of 2 nodes while keeping the BST relationship valid. Here’s a replica of an image from CLRS^{2} to illustrate the procedure: we want to change this

into this:

Suppose that the BST properties are valid for the first graph. It is easy to see that they keep holding for the second:

- The subtree
`a`

had keys smaller than`x`

and is still`x`

‘s left sub-tree after the rotation - The subtree
`b`

had keys larger than`x`

, and is still`x`

‘s right sub-tree after the rotation; it was also in`y`

‘s sub-tree, and still is after the rotation `c`

remains`y`

‘s right sub-tree

The tree class starts like:

1 | class RBTree { |

The code for the rotate-right operation looks like this:

1 | // static |

## Test *RightRotate*

The code above makes just some pointer manipulation to ensure we get in the right layout, as shown in Figure 2. Since we don’t have an `Insert`

function yet, we test this by first creating an `RBTree`

object and wiring up the nodes manually. We can build a test fixture in doctest like this:

1 | class ManualTreeCtor { |

which just implements a tree like this:

We now test the cases for `y`

being the root or not:

1 | TEST_CASE_FIXTURE(ManualTreeCtor, "right-rotate non-root") { |

While I won’t show the code for the left-rotation, the logic is exactly the same (but for going from the configuration of Fig. 2 to the one in Fig. 1).

With these operations in place, we can now implement the insertion operation.

## Insertion, and the node’s color

RB trees’ nodes have an additional attribute: a color which can be either `RED`

or `BLACK`

. It is common to assign some `NIL`

value to all leaves (I implemented it via a nullptr, without an explicit node with that color^{3}). The invariants I mentioned above can be expressed via five properties^{3} :

- Each node is either red or black.
- The root is black.
- All leaves (NIL) are black
^{4}. - If a node is red, then both its children are black.
- Every path from a given node to any of its descendant NIL nodes contains the same number of black nodes.

These invariants can be kept when inserting. We need to reason about the sibling of the node-to-be-inserted’s parent, which we can refer to as the node’s *uncle*. After each insertion, we run an operation `InsertFixup`

to restore the invariants that might have been violated. This is an implementation:

1 | // static |

The `InsertFixup`

method for node *z* is a bit messy because there are many checks for null pointers, but the two branches of the `if`

statement do very symmetric operations (inverting left and right), and the branch selected depends on *z*‘s parent being a left or right child.

1 | // static |

## Conclusion

I’ve said a few words about Red-Black trees, a kind of binary search trees that have the property of remaining balanced when inserting and deleting nodes. In this post, I’ve shown the basic `rotate`

operation and shown an implementation of `Insert`

. In the next episodes, I’ll implement a `DeleteNode`

operation, and then benchmark the tree against a classic binary search tree to see how much my implementation keeps its promises.

- 1.I am somehow simplifying by not counting the keys equal to
`n.k`

. However, that is a small issue for which I've tried a couple of easy solutions, like either relaxing the constraint on either sub-tree (e.g., smaller-than-or-equal rather than smaller-than for the left sub-tree), or using a counter in each node for repeated keys. It's the typical tiny implementation detail algorithm courses tend to skip over. ↩ - 2.https://en.wikipedia.org/wiki/Introduction_to_Algorithms ↩
- 3.https://en.wikipedia.org/wiki/Red%E2%80%93black_tree ↩
- 4.I haven't found this decision to limit the implementation of
`Insert`

, but I might revisit it when I'll finally understand what it's for. In particular, I plan to use a single node with no value and only the color black, which all other leaves will point to. ↩