Red-black Trees
Red-black trees are a height-balanced binary search tree, much like 2-3 trees and AVL trees. Its distinguishing properties are as follows:
- Every node has a color, red or black (in numeric terms, a
0
or1
). - The tree's root is always black.
- The null nodes are always black.
- If a node is red, then its parent and its chilren must be black.
- All newly inserted nodes are initially red.
- The height of a red-black tree is bounded as follows:
Insertion
To illustrate insertion, we use the following set of keys:
Start with the first key, 10. This creates the node:
Note that this node must have the color black, per Property 2. Next, we insert the key 20:
Then we insert the key 30:
Now we've run into trouble. Under Property 4, that 30 must be black. This situation is called a red-red conflict. For brevity, we'll call the node causing this conflict — here, 30 — the rascal. Red-red conflicts are resolved through recoloring and rotation. We examine each in turn.
Recoloring
The easiest approach is recoloring. To illustrate this approach, suppose we had the following tree:
Above, we have a red-red conflict resulting from the rascal has the parent the pibling and the grandparent In recoloring, we perform the following procedure:
- Starting from the rascal to the root:
- Change 's color to black.
- Change 's color to black.
- Change 's color to red, unless is the root.
The end result:
Rotation
Recoloring only addresses the situation where the rascal has a pibling. It does not address the situation where the rascal has no piblings. There are two such cases:
For both cases, we must rotate, similar to how rotations are done with AVL trees. In case 1, we perform a zig-zig rotation, and in case 2, we perform a zig-zag rotation. The end result for both:
In sum, we have the following requirements during the insertion process:
- If a red-red conflict occurs, do the following:
- If the rascal has a black pibling, perform a recoloring.
- Else:
- If the rascal is the left-child of its parent, perform a zig-zig rotation.
- If the rascal is the right-child of its parent, perform a zig-zag rotation.
Returning to our insertion process, we see that the rascal has no pibling and is the right-child of its parent. So, we perform a zig-zag rotation (equivalent to the RR-rotation we saw with AVL trees).
Now we add the next key, 50:
We have another red-red conflict. This time, the rascal has a pibling, and thati pibling is red. Accordingly, we perform a recoloring:
Now we insert the next key, 40. This node becomes the left-child of 50:
We get another red-red conflict. The parent is red, and the rascal 40 has no piblings. So, we perform a zig-zag rotation: