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 which have single incoming edge are BLACK in color.
Characteristics of LLRB
1. Root node is Always BLACK in color.
2. Every new Node inserted is always RED in color.
3. Every NULL child of a node is considered as BLACK in color.
Eg : only 40 is present in tree.
root | 40 <-- as 40 is the root so it / is also Black in color. NULL NULL <-- Black in color.
4. There should not be a node which has RIGHT RED child and LEFT BLACK child(or NULL child as all NULLS are BLACK), if present Left rotate the node, and swap the colors of current node and its LEFT child so as to maintain consistency for rule 2 i.e., new node must be RED in color.
CASE 1. root root | || 40 LeftRotate(40) 50 / \ ---> / NULL 50 40 NULL root | ColorSwap(50, 40) 50 ---> // 40 NULL
5. There should not be a node which has LEFT RED child and LEFT RED grandchild, if present Right Rotate the node and swap the colors between node and it’s RIGHT child to follow rule 2.
CASE 2. root root | || 40 RightRotate(40) 20 // ---> // 20 50 10 40 // 10 50 root | ColorSwap(20, 40) 20 ---> // \ 10 40 50
6. There should not be a node which has LEFT RED child and RIGHT RED child, if present Invert the colors of all nodes i. e., current_node, LEFT child, and RIGHT child.
CASE 3. root root | !color(20, 10, 30) || 20 ---> 20 // \ / 10 30 10 30 root As the root is always black | ---> 20 / 10 30
Why are we following the above mentioned rules? Because by following above characteristics/rules we are able to simulate all the red-black tree’s properties without caring about the complex implementation of it.
Insert the following data into LEFT LEANING RED-BLACK TREE and display the inorder traversal of tree. Input : 10 20 30 40 50 25 Output : 10 20 30 40 50 25 root | 40 // 20 50 / 10 30 // 25
Insertions in the LLRB is exactly like inserting into a Binary search tree . The difference is that that After we insert the node into the tree we will retrace our steps back to root and try to enforce the above rules for LLRB.
While doing the above rotations and swapping of color it may happen that our root becomes RED in color so we also. We have to make sure that our root remains always BLACK in color.
left rotation!! left rotation!! left rotation!! 10 20 25 30 40 50
Time Complexity: O(log n)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.