The insertion procedure in a red-black tree is similar to a binary search tree i.e., the insertion proceeds in a similar manner but after insertion of nodes x into the tree T, we color it red. In order to guarantee that the red-black properties are preserved, we then fix up the updated tree by changing the color of the nodes and performing rotations. Let us write the pseudo code for insertion.
Given are the two procedures followed for insertion into a Red-Black Tree:
Procedure 1: This is used to insert an element in a given Red-Black Tree. It involves the method of insertion used in binary search tree.
Procedure 2: Whenever any node is inserted in a tree, it is made red, and after insertion, there may be chances of loosing Red-Black Properties in a tree, and, so, some cases are to be considered in order to retain those properties.
During the insertion procedure, the inserted node is always red. After inserting a node, it is essential to notify that which of the red-black properties are violated. Now let us look at the execution of fix up. Let Z be the node that is to be inserted & is colored red. At the starting of each iteration of the loop,
1. Node Z is red
2. If P(Z) is the root, then P(Z) is black
3. Now if any of the properties that mean property 2 is violated if Z is the root and is red OR when property 4 is violated if both Z and P (Z) are red, then we consider 3 cases in the fix up algorithm. Now let us discuss those cases.
Case 1(Z's uncle y is red): This is executed while both parent of Z (P(Z)) and uncle of Z, i.e. y are red in color. thus, we can maintain one of the property of Red-Black tree by making both P(Z) and y black and making point of P(Z) to be red, thus maintaining one more property. Now, this while loop is repeated again till color of y is black.
Case 2 (Z's uncle is black and Z is the right child): thus, make parent of Z to be Z itself and apply left rotation to newly obtained Z.
Case 3 (Z's uncle is black and Z is the left child): This case executes by making parent of Z as black and P(P(Z)) as red and then performing right rotation to it i.e., to (P(Z)).