I am new to data structures. I have gone through red-black tree insertion algorithm implementation. I am not able to understand, how algorithm takes care of insertion of sorted values.
Let me illustrate with data set [10, 5, 2].
So, Initial 10 will be inserted and will be the root of the tree and its color will be black. 10
Next, we'll be adding 5, under root 10. The color of 5 will be red(As of now, It doesn't violate any of the properties).
Now, we'll add be adding 2. After addition, the tree will look like :- Addition of 2(whose color is red) will violate rule of not allowing red child under red parent. There're 3 cases in Red-black tree :- All the three cases assume that parentOf(newlyInsertedNode) have sibling. But in my case parentOf(2) = 5 doesn't have sibling. So, How this scenario will be dealt in the Red-black tree algorithm.
The specifics of red-black trees might differ a bit depending on the article/book/implementation.
There, is, however, a very common variant used by Introduction To Algorithms (CLRS). In this variant, there are special NIL
children. A NIL
child contains a special "Null" key, indicating that it is just a leaf.
The invariants for RB trees are:
NIL
) is black.Note, in particular, invariant 3 - NIL
nodes are black.
Using this common variant, your RB tree has 4 additional nodes:
the right child of 10
The right child of 5
The left and right children of 2
The right child of 5 is the sibling which you're missing.