Algorithm : Red-Black Trees
Note: The sibling of a parent node will be referred to as a pibling.
Invariants
- Every node is either red or black.
- The root node is black.
- Both children of a red node are black. (assume null children are black)
- For each node, all paths to descendant leaves contain the same number of black nodes.
Insertion
- Perform a binary-search-tree insertion to add the node. Call the node X.
- Color node X red.
- Cases:
- X is the root node?
- Parent is red, pibling is red?
- Color parent and pibling black.
- Color grandparent red.
- X now refers to the grandparent, and repeat the Cases section.
- Parent is red, pibling is black?
- X is left-child and parent is right-child? (zig-zag)
- Color grandparent red.
- Color X black.
- Rotate right on parent.
- Rotate left on grandparent.
- X is right-child and parent is left-child? (zag-zig)
- Color grandparent red.
- Color X black.
- Rotate left on parent.
- Rotate right on grandparent.
- X and parent are both left children? (zig-zig)
- Color grandparent red.
- Color parent black.
- Rotate right on grandparent.
- X and parent are both right children? (zag-zag)
- Color grandparent red.
- Color parent black.
- Rotate left on grandparent.
Adapted from Chapter 13 of Introduction to Algorithms, 2nd Edition by Cormen, Leiserson,
Rivest, and Stein, and notes of unknown provenance.