![]() |
VOOZH | about |
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.
Recolouring is the change in colour of the node i.e. if it is red then change it to black and vice versa. It must be noted that the colour of the NULL node is always black. Moreover, we always try recolouring first, if recolouring doesn't work, then we go for rotation. Following is a detailed algorithm. The algorithms have mainly two cases depending upon the colour of the uncle. If the uncle is red, we do recolour. If the uncle is black, we do rotations and/or recolouring.
First, you have to insert the node similarly to that in a binary tree and assign a red colour to it. Now, if the node is a root node then change its colour to black, but if it is not then check the colour of the parent node. If its colour is black then donβt change the colour but if it is not i.e. it is red then check the colour of the nodeβs uncle. If the nodeβs uncle has a red colour then change the colour of the nodeβs parent and uncle to black and that of grandfather to red colour and repeat the same process for him (i.e. grandfather).If grandfather is root then don't change grandfather to red colour.
But, if the nodeβs uncle has black colour then there are 4 possible cases:
Now, after these rotations, re-color according to rotation case (check algorithm for details).
Let x be the newly inserted node.
Re-coloring after rotations:
For Left Left Case [3.b (i)] and Right Right case [3.b (iii)], swap colors of grandparent and parent after rotations
For Left Right Case [3.b (ii)]and Right Left Case [3.b (iv)], swap colors of grandparent and inserted node after rotations
Example: Creating a red-black tree with elements 3, 21, 32 and 15 in an empty tree.
Solution:
Final Tree Structure:
Please refer C Program for Red Black Tree Insertion for complete implementation of the above algorithm.
Red-Black Tree | Set 3 (Delete)
The following code also implements tree insertion as well as tree traversal, at the end you can visualize the constructed tree too!!!.
1 1 4 1 4 6 1 3 4 6 1 3 4 5 6 1 3 4 5 6 7 1 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1
Time Complexity : O(log N) , here N is the total number of nodes in the red-black trees.
Space Complexity: O(N), here N is the total number of nodes in the red-black trees.