![]() |
VOOZH | about |
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.
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.
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)
Following are operations to be performed in four subcases when uncle is BLACK.
Left Left Case (See g, p and x)
Left Right Case (See g, p and x)
Right Right Case (See g, p and x)
Right Left Case (See g, p and x)
Examples of Insertion
Implementation:
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.