In Bottom-Up insertion of Red-Black Trees, “simple” Binary Search Tree insertion is used, followed by correction of the RB-Tree Violations on the way back up to the root. This can be done easily with the help of recursion. While in Top-Down Insertion, the corrections are done while traversing down the tree to the insertion point. When the actual insertion is done, no further corrections are needed, so no need to traverse back up the tree.
Therefore, the goal of Top-Down insertion is to traverse from the root to the insertion point in such a way that RB properties are maintained. This iterative approach thus makes Top-Down insertion faster than Bottom-Up insertion.
The two basic operations to perform for fixing violations and balancing are-
Following is the detailed Algorithm
The main goal of this algorithm is to create an insertion point at which the parent of the new node is Black, or the uncle of the new node is black.
Let N be the new node to be inserted.
- If Y and Z are Black:
- If X’s Parent is Black:
- X’s Parent P is Red, Grandparent is Black and X and P are both left OR right children of Grandparent G:
perform Simple BST insertion. Insert new node N as the left/right child of Y OR Z and make the colour of the newly inserted node as red.
Then Recolor X, Y, Z and continue Down the tree.
- Recolor X, Y, Z
- Rotate P around G
- Color P black
- Color G red
If violations exist continue with further cases.
- Recolor X, Y, Z
- Rotate X around P
- Rotate X around G
- Recolor X and G
Insert New Node N at the required Position.
Insert Node 3 in the RB-Tree below –
Below the implementation of the following approach:
The LevelOrder Traversalof the tree is: | is | B | gold | old | | gold | R | NULL | NULL | | old | R | NULL | NULL | Inserting a word in the tree: | is | B | gold | old | | gold | B | forever | NULL | | old | B | NULL | NULL | | forever | R | NULL | NULL |
Red Black Trees – UMBC CSEE
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.