Red-Black Trees

Pseudo code for inserting a new node z into an existing binary search tree T:

BST-INSERT(T, z)
    parent = NIL; // will point to parent of new node
    curr = T.root;

    // Find the correct spot in BST
    while(curr != NIL){
        parent = curr;
        if z.value < curr.value
            curr = curr.left
        else
            curr = curr.right
    }

    // Set new node's parent pointer
    z.parent = parent;

    // Set parent's child pointer
    if parent == NIL
        T.root = z; // The tree was empty
    elseif z.value < parent.value
        parent.left = z;
    else
        parent.right = z;
END

Modified pseudo code for inserting a new node z into an existing red-black tree T:

RB-INSERT(T, z)
    parent = T.nil; // will point to parent of new node
    curr = T.root;

    // Find the correct spot in BST
    while(curr != T.nil){
        parent = curr;
        if z.value < curr.value
            curr = curr.left
        else
            curr = curr.right
    }

    // Set new node's parent pointer
    z.parent = parent;

    // Set parent's child pointer
    if parent == T.nil
        T.root = z; // The tree was empty
    elseif z.value < parent.value
        parent.left = z;
    else
        parent.right = z;

    // Additional considerations for red-black trees
    z.left = T.nil;
    z.right = T.nil;
    z.color = RED;
    RB-INSERT-FIXUP(T,z);
END

Pseudocode for fixing a red-black tree after an insert:

RB-INSERT-FIXUP(T, z)
    while(z.parent.color == RED){
        // set parent and grandparent
        parent = z.parent;
        grandparent = z.parent.parent;

        // z's parent is a left child
        if(parent == grandparent.left){
            uncle = grandparent.right;

            // Case One - uncle is red
            if(uncle.color == RED){
                parent.color = BLACK;
                uncle.color = BLACK;
                grandparent.color = RED
                z = grandparent;
            }
            else{
                // Case Two - uncle is black and z is an inside node
                if(z == parent.right){
                    LEFT-ROTATE(T, z, parent);
                    z = parent;
                }
                // Case Three - uncle is black and z is an outside node
                RIGHT-ROTATE(T, parent, grandparent);
                parent.color = BLACK;
                grandparent.color = RED;
            }
        }
        else{
            //Same as above except left and right are switched
        }
    T.root.color = BLACK
END