The Wayback Machine - https://web.archive.org/web/20240910111500/https://www.geeksforgeeks.org/c-program-red-black-tree-insertion/
Open In App

C Program for Red Black Tree Insertion

Last Updated : 21 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Following article is extension of article discussed here.
In AVL tree insertion, we used rotation as a tool to do balancing after insertion caused imbalance. In Red-Black tree, we use two tools to do balancing.

  1. Recoloring 
  2. Rotation

We try recoloring first, if recoloring doesn’t work, then we go for rotation. Following is detailed algorithm. The algorithms has mainly two cases depending upon the color of uncle. If uncle is red, we do recoloring. If uncle is black, we do rotations and/or recoloring.
Color of a NULL node is considered as BLACK.

Let x be the newly inserted node. 

  1. Perform standard BST insertion and make the color of newly inserted nodes as RED.
  2. If x is root, change color of x as BLACK (Black height of complete tree increases by 1).
  3. Do following if color of x’s parent is not BLACK or x is not root. 
    1. If x’s uncle is RED (Grand parent must have been black from property 4) 
      1. Change color of parent and uncle as BLACK. 
      2. color of grand parent as RED. 
      3.     3. Change x = x’s grandparent, repeat steps 2 and 3 for new x. 
         

redBlackCase2

      2. If x’s uncle is BLACK, then there can be four configurations for x, x’s parent (p) and x’s grandparent (g) (This is similar to AVL Tree) 

  1. Determine the configuration:
    1. Left Case (p is left child of g and x is left child of p).
    2. Left Right Case (p is left child of g and x is right child of p).
    3. Right Right Case (Mirror of case a).
    4. Right Left Case (Mirror of case c).
  2. Change x = x’s parent, repeat steps 2 and 3 for new x.

Following are operations to be performed in four subcases when uncle is BLACK.

All four cases when Uncle is BLACK

Left Left Case (See g, p and x) 

redBlackCase3a

Left Right Case (See g, p and x) 

redBlackCase3b

Right Right Case (See g, p and x) 

redBlackCase3c

Right Left Case (See g, p and x) 

redBlackCase3d

Examples of Insertion 

Examples

Implementation:

C




/** C implementation for
    Red-Black Tree Insertion
    This code is provided by
    costheta_z **/
#include <stdio.h>
#include <stdlib.h>
 
// Structure to represent each
// node in a red-black tree
struct node {
    int d; // data
    int c; // 1-red, 0-black
    struct node* p; // parent
    struct node* r; // right-child
    struct node* l; // left child
};
 
// global root for the entire tree
struct node* root = NULL;
 
// function to perform BST insertion of a node
struct node* bst(struct node* trav,
                      struct node* temp)
{
    // If the tree is empty,
    // return a new node
    if (trav == NULL)
        return temp;
 
    // Otherwise recur down the tree
    if (temp->d < trav->d)
    {
        trav->l = bst(trav->l, temp);
        trav->l->p = trav;
    }
    else if (temp->d > trav->d)
    {
        trav->r = bst(trav->r, temp);
        trav->r->p = trav;
    }
 
    // Return the (unchanged) node pointer
    return trav;
}
 
// Function performing right rotation
// of the passed node
void rightrotate(struct node* temp)
{
    struct node* left = temp->l;
    temp->l = left->r;
    if (temp->l)
        temp->l->p = temp;
    left->p = temp->p;
    if (!temp->p)
        root = left;
    else if (temp == temp->p->l)
        temp->p->l = left;
    else
        temp->p->r = left;
    left->r = temp;
    temp->p = left;
}
 
// Function performing left rotation
// of the passed node
void leftrotate(struct node* temp)
{
    struct node* right = temp->r;
    temp->r = right->l;
    if (temp->r)
        temp->r->p = temp;
    right->p = temp->p;
    if (!temp->p)
        root = right;
    else if (temp == temp->p->l)
        temp->p->l = right;
    else
        temp->p->r = right;
    right->l = temp;
    temp->p = right;
}
 
// This function fixes violations
// caused by BST insertion
void fixup(struct node* root, struct node* pt)
{
    struct node* parent_pt = NULL;
    struct node* grand_parent_pt = NULL;
 
    while ((pt != root) && (pt->c != 0)
           && (pt->p->c == 1))
    {
        parent_pt = pt->p;
        grand_parent_pt = pt->p->p;
 
        /*  Case : A
             Parent of pt is left child
             of Grand-parent of
           pt */
        if (parent_pt == grand_parent_pt->l)
        {
 
            struct node* uncle_pt = grand_parent_pt->r;
 
            /* Case : 1
                The uncle of pt is also red
                Only Recoloring required */
            if (uncle_pt != NULL && uncle_pt->c == 1)
            {
                grand_parent_pt->c = 1;
                parent_pt->c = 0;
                uncle_pt->c = 0;
                pt = grand_parent_pt;
            }
 
            else {
 
                /* Case : 2
                     pt is right child of its parent
                     Left-rotation required */
                if (pt == parent_pt->r) {
                    leftrotate(parent_pt);
                    pt = parent_pt;
                    parent_pt = pt->p;
                }
 
                /* Case : 3
                     pt is left child of its parent
                     Right-rotation required */
                rightrotate(grand_parent_pt);
                int t = parent_pt->c;
                parent_pt->c = grand_parent_pt->c;
                grand_parent_pt->c = t;
                pt = parent_pt;
            }
        }
 
        /* Case : B
             Parent of pt is right
             child of Grand-parent of
           pt */
        else {
            struct node* uncle_pt = grand_parent_pt->l;
 
            /*  Case : 1
                The uncle of pt is also red
                Only Recoloring required */
            if ((uncle_pt != NULL) && (uncle_pt->c == 1))
            {
                grand_parent_pt->c = 1;
                parent_pt->c = 0;
                uncle_pt->c = 0;
                pt = grand_parent_pt;
            }
            else {
                /* Case : 2
                   pt is left child of its parent
                   Right-rotation required */
                if (pt == parent_pt->l) {
                    rightrotate(parent_pt);
                    pt = parent_pt;
                    parent_pt = pt->p;
                }
 
                /* Case : 3
                     pt is right child of its parent
                     Left-rotation required */
                leftrotate(grand_parent_pt);
                int t = parent_pt->c;
                parent_pt->c = grand_parent_pt->c;
                grand_parent_pt->c = t;
                pt = parent_pt;
            }
        }
    }
}
 
// Function to print inorder traversal
// of the fixated tree
void inorder(struct node* trav)
{
    if (trav == NULL)
        return;
    inorder(trav->l);
    printf("%d ", trav->d);
    inorder(trav->r);
}
 
// driver code
int main()
{
    int n = 7;
    int a[7] = { 7, 6, 5, 4, 3, 2, 1 };
 
    for (int i = 0; i < n; i++) {
 
        // allocating memory to the node and initializing:
        // 1. color as red
        // 2. parent, left and right pointers as NULL
        // 3. data as i-th value in the array
        struct node* temp
            = (struct node*)malloc(sizeof(struct node));
        temp->r = NULL;
        temp->l = NULL;
        temp->p = NULL;
        temp->d = a[i];
        temp->c = 1;
 
        // calling function that performs bst insertion of
        // this newly created node
        root = bst(root, temp);
 
        // calling function to preserve properties of rb
        // tree
        fixup(root, temp);
          root->c = 0;
    }
 
    printf("Inorder Traversal of Created Tree\n");
    inorder(root);
 
    return 0;
}


Output

Inorder Traversal of Created Tree
1  2  3  4  5  6  7  

Level Order Traversal of Created Tree
6  4  7  2  5  1  3  

Time Complexity:  O(log n), as the height of red-black tree is O(log n) at most, and complexity of rotation is constant.
Auxiliary Space:  O(n),  here ‘n’ is the number of nodes in the red-black trees.



Previous Article
Next Article

Similar Reads

Left Leaning Red Black Tree (Insertion)
Prerequisites : Red - Black Trees.A left leaning Red Black Tree or (LLRB), is a variant of red black tree, which is a lot easier to implement than Red black tree itself and guarantees all the search, delete and insert operations in O(logn) time. Which nodes are RED and Which are Black ? Nodes which have double incoming edge are RED in color. Nodes
15+ min read
Insertion in Red-Black Tree
In the previous post, we discussed the introduction to Red-Black Trees. In this post, insertion is discussed. In AVL tree insertion, we used rotation as a tool to do balancing after insertion. In the Red-Black tree, we use two tools to do the balancing.  RecoloringRotationRecolouring is the change in colour of the node i.e. if it is red then change
15+ min read
Count of graphs formed by changing color of any red-colored node with black parent to black
Given a directed graph G consisting of N nodes and N-1 edges, and a positive integer K, and initially, all the nodes of the graph are red except for K, which is black, the task is to count the number of different possible graphs formed by changing the color of any red-colored node to black, only if their parent is colored black, any number of times
8 min read
Check if a given Binary Tree is height balanced like a Red-Black Tree
In a Red-Black Tree, the maximum height of a node is at most twice the minimum height (The four Red-Black tree properties make sure this is always followed). Given a Binary Search Tree, we need to check for following property. For every node, length of the longest leaf to node path has not more than twice the nodes on shortest path from node to lea
9 min read
Red Black Tree vs AVL Tree
In this post, we will compare Red-Black Tree and AVL Tree. Red Black Tree: Properties: Self-Balancing is provided by painting each node with two colors(Red or Black).When the Tree is modified, a new tree is subsequently rearranged and repainted.It requires 1 bit of color information for each node in the tree.Time complexity: O(logn). Constraints ma
2 min read
Applications, Advantages and Disadvantages of Red-Black Tree
Red-Black Tree is one type of self-balancing tree where each node has one extra bit that is often interpreted as colour of the node. This bit (the colour) is used to ensure that the tree remains balanced. Properties of Red-Black Trees: Red-Black Trees have the accompanying properties: Each hub has a variety.The root is black.Each leaf is an excepti
4 min read
What is the difference between Heap and Red-Black Tree?
What is Heap? A Heap is a special Tree-based data structure in which the tree is a complete binary tree. There are two types of heap - Min heap and Max heap. To learn more about heap, go through the following article: Introduction to Heap What is a Red-Black Tree?The red-Black tree is a self-balancing binary search tree in which each node contains
2 min read
Red-Black Tree definition & meaning in DSA
A red-black tree is a self-balancing binary search tree in which each node of the tree has an color, which can either be red or black. Characteristics of Red Black Tree:The root node is always black and each node can be either black or red.Every leaf node of the red-black tree is black.The children of red nodes are black.The number of black nodes w
2 min read
Deletion in Red-Black Tree
Deletion in a red-black tree is a bit more complicated than insertion. When a node is to be deleted, it can either have no children, one child or two children. Here are the steps involved in deleting a node in a red-black tree:If the node to be deleted has no children, simply remove it and update the parent node.If the node to be deleted has only o
15+ min read
Optimal sequence for AVL tree insertion (without any rotations)
Given an array of integers, the task is to find the sequence in which these integers should be added to an AVL tree such that no rotations are required to balance the tree. Examples : Input : array = {1, 2, 3} Output : 2 1 3 Input : array = {2, 4, 1, 3, 5, 6, 7} Output : 4 2 6 1 3 5 7 Approach : Sort the given array of integers.Create the AVL tree
8 min read
Proto Van Emde Boas Tree | Set 3 | Insertion and isMember Query
Please see previous articles on Proto Van Emde Boas Tree to understand these properly. Procedure for Insert: Base Case: If the size of Proto-VEB is 2 then assign true to the bit array( Here we in code we assign Proto-VEB(1) due to recursive structure and so now it is not nullptr and it act as true ) at the position of key.Until we reach at the base
9 min read
Insertion in n-ary tree in given order and Level order traversal
Given a set of parent nodes where the index of the array is the child of each Node value, the task is to insert the nodes as a forest(multiple trees combined together) where each parent could have more than two children. After inserting the nodes, print each level in a sorted format. Example: Input: arr[] = {5, 3, -1, 2, 5, 3} Output:-1 231 5Input:
10 min read
Van Emde Boas Tree | Set 2 | Insertion, Find, Minimum and Maximum Queries
It is highly recommended to see previous articles on Van Emde Boas Tree first. Procedure for Insert : If no keys are present in the tree then simply assign minimum and maximum of the tree to the key.Otherwise we will go deeper in the tree and do the following:If the key we want to insert is less than the current minimum of the tree, then we swap bo
15+ min read
m-Way Search Tree | Set-2 | Insertion and Deletion
Insertion in an m-Way search tree: The insertion in an m-Way search tree is similar to binary trees but there should be no more than m-1 elements in a node. If the node is full then a child node will be created to insert the further elements. Let us see the example given below to insert an element in an m-Way search tree.Example: To insert a new el
15+ min read
POTD Solutions | 23 Nov’ 23 | AVL Tree Insertion
Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of AVL Trees but will also help you build up problem-solving skills. We recommend you to try this problem on our GeeksforGeeks Pract
12 min read
Search and Insertion in K Dimensional tree
What is K dimension tree? A K-D Tree(also called as K-Dimensional Tree) is a binary search tree where data in each node is a K-Dimensional point in space. In short, it is a space partitioning(details below) data structure for organizing points in a K-Dimensional space. A non-leaf node in K-D tree divides the space into two parts, called as half-spa
15+ min read
ScapeGoat Tree | Set 1 (Introduction and Insertion)
A ScapeGoat tree is a self-balancing Binary Search Tree like AVL Tree, Red-Black Tree, Splay Tree, ..etc. Search time is O(Log n) in worst case. Time taken by deletion and insertion is amortized O(Log n)The balancing idea is to make sure that nodes are ? size balanced. ? size balanced means sizes of left and right subtrees are at most ? * (Size of
15+ min read
Threaded Binary Tree | Insertion
We have already discuss the Binary Threaded Binary Tree.Insertion in Binary threaded tree is similar to insertion in binary tree but we will have to adjust the threads after insertion of each element. C representation of Binary Threaded Node: struct Node { struct Node *left, *right; int info; // false if left pointer points to predecessor // in Ino
13 min read
Insertion in a Binary Tree in level order
Given a binary tree and a key, insert the key into the binary tree at the first position available in level order. The idea is to do an iterative level order traversal of the given tree using queue. If we find a node whose left child is empty, we make a new key as the left child of the node. Else if we find a node whose right child is empty, we mak
7 min read
Insertion in Splay Tree
It is recommended to refer following post as prerequisite of this post.Splay Tree | Set 1 (Search)As discussed in the previous post, Splay tree is a self-balancing data structure where the last accessed key is always at root. The insert operation is similar to Binary Search Tree insert with additional steps to make sure that the newly inserted key
15+ min read
Insertion in a B+ tree
Prerequisite: Introduction of B+ treesIn this article, we will discuss that how to insert a node in B+ Tree. During insertion following properties of B+ Tree must be followed:  Each node except root can have a maximum of M children and at least ceil(M/2) children.Each node can contain a maximum of M - 1 keys and a minimum of ceil(M/2) - 1 keys.The
15+ min read
Insertion in Binary Search Tree (BST)
Given a BST, the task is to insert a new node in this BST. Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf
15 min read
Insertion in an AVL Tree
AVL Tree:AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes.  Example of AVL Tree:  The above tree is AVL because the differences between the heights of left and right subtrees for every node are less than or equal to 1. Example of a Tree that i
15+ min read
Minimum number of Apples to be collected from trees to guarantee M red apples
There are different kinds of apple trees in the four directions (East, West, North, South), which may grow both red and green apples such that each tree grows exactly K apples, in the following manner: N - number of trees to the north does not have red apples.S - number of trees to the south does not have green apples.W - number of trees in the wes
7 min read
Count ways of selecting X red balls and Y blue balls
Given integers A, B, C, and D, There are two boxes First Box has A red balls and B blue balls and the second box has C red balls and D blue balls, the task is to count ways to select 3 red balls and 3 blue balls so that there are 3 balls drawn from the first box and 3 balls drawn from the second box. (Print the answer modulo 109 + 7). Examples: Inp
15+ min read
Maximize the number of boxes using red and yellow balls
We are given R red balls and Y yellow balls to fill in boxes. We can fill a box using one of the two ways: Using A red balls and B yellow ballsUsing B red balls and A yellow balls. Maximize the number of boxes we can fill. Note: One ball can belong to only one box Examples: Input: R = 10, Y = 12, A = 2, B = 5 Output: 3 Explanation: First and Second
10 min read
Javascript Program For Insertion Sort In A Singly Linked List
We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert current node in sorted way in sorted or result list. 3
3 min read
Count of node sequences of length K consisting of at least one black edge
Given a tree consisting of N nodes numbered from [1, N] and is colored either black(denoted by 1) or green(denoted by 0), the task is to count the number of sequences of length K [a1, a2, ..aK] such that the path taken between consecutive nodes is the shortest one and the edges covered consist of at least one black edge. Since the answer can be lar
12 min read
Maximum difference of count of black and white vertices in a path containing vertex V
Given a Tree with N vertices and N - 1 edge where the vertices are numbered from 0 to N - 1, and a vertex V present in the tree. It is given that each vertex in the tree has a color assigned to it which is either white or black and the respective colors of the vertices are represented by an array arr[]. The task is to find the maximum difference be
9 min read
Maximize boxes required to keep at least one black and one white shirt
Given three numbers W, B, and O representing the quantities of white, black, and other colors shirts respectively, the task is to find the maximum number of boxes required such that each box contains three shirts consisting of at least one white and black shirt using the given quantity of shirts. Examples: Input: W = 3, B = 3, O = 1Output: 2Explana
7 min read