VOOZH about

URL: https://www.geeksforgeeks.org/dsa/red-black-trees-top-down-insertion/

⇱ Red-Black Trees | Top-Down Insertion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Red-Black Trees | Top-Down Insertion

Last Updated : 11 Jul, 2025

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- 

  • Recoloring
  • Rotation


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. 

  1. If Y and Z are Black:
  2. If X's Parent is Black:
  3. X’s Parent P is Red, Grandparent is Black and X and P are both left OR right children of Grandparent G:
    • Recolor X, Y, Z
    • Rotate P around G
    • Color P black
    • Color G red
  4. X’s Parent is Red, Grandparent is Black and X and P are opposite children of Grandparent G
    • Recolor X, Y, Z
    • Rotate X around P
    • Rotate X around G
    • Recolor X and G

Below the implementation of the following approach: 


Output
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 | 

References:
Red Black Trees - UMBC CSEE

Comment
Article Tags:
Article Tags: