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
- Generic Trees(N-array Trees)
- Total number of possible Binary Search Trees and Binary Trees with n keys
- AVL Tree | Set 1 (Insertion)
- Insertion and Deletion in Heaps
- C Program for Red Black Tree Insertion
- ScapeGoat Tree | Set 1 (Introduction and Insertion)
- Threaded Binary Tree | Insertion
- Optimal sequence for AVL tree insertion (without any rotations)
- Insertion in a Binary Tree in level order
- Left Leaning Red Black Tree (Insertion)
- Van Emde Boas Tree | Set 2 | Insertion, Find, Minimum and Maximum Queries
- Insertion in n-ary tree in given order and Level order traversal
- Binary Search Tree | Set 1 (Search and Insertion)
- AA Trees | Set 1 (Introduction)
- B*-Trees implementation in C++
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.