The traditional algorithm for insertion in an RB tree colors new nodes
red. This is a good choice, because it often means that no
rebalancing is necessary, but it is not the only possible choice.
This section implements an alternate algorithm for insertion into an
RB tree that colors new nodes black.

The outline is the same as for initial-red insertion. We change the
newly inserted node from red to black and replace the rebalancing
algorithm:

The remaining task is to devise the rebalancing algorithm.
Rebalancing is always necessary, unless the tree was empty before
insertion, because insertion of a black node into a nonempty tree
always violates rule 2. Thus, our invariant is that we have a rule 2
violation to fix.

More specifically, the invariant, as implemented, is that at the top
of each trip through the loop, stack pa[] contains the chain of
ancestors of a node that is the black root of a subtree whose
black-height is 1 more than it should be. We give that node the name
q. There is one easy rebalancing special case: if node q has a
black parent, we can just recolor q as red, and we're done. Here's
the loop:

Consider rebalancing where insertion was on the left side of q's
grandparent. We know that q is black and its parent pa[k - 1] is
red. Then, we can divide rebalancing into three cases, described
below in detail. (For additional insight, compare these cases to the
corresponding cases for initial-red insertion.)

Case 1: q's uncle is red

If q has an red “uncle” y, then we recolor q red and pa[k - 1] and y black. This fixes the immediate problem, making the
black-height of q equal to its sibling's, but increases the
black-height of pa[k - 2], so we must repeat the rebalancing process
farther up the tree:

Case 2: q is the left child of pa[k - 1]

If q is a left child, then call q's parent y and its grandparent
x, rotate right at x, and recolor q, y, and x. The effect
is that the black-heights of all three subtrees is the same as before
q was inserted, so we're done, and break out of the loop.

Case 3: q is the right child of pa[k - 1]

If q is a right child, then we rotate left at its parent, which we
here call x. The result is in the form for application of case 2,
so after the rotation, we relabel the nodes to be consistent with that
case.