Constructing a Red-Black Tree: Inserting 123456789
Introduction: A Red-Black Tree (RB Tree) is a self-balancing binary search tree. It is one of the simplest and most efficient self-balancing data structures, which helps in maintaining order and optimal complexity during operations.
Properties of a Red-Black Tree
Before delving into the insertion process, let's revisit the key properties of a Red-Black Tree:
Each node is either red or black. The root is always black. All leaves (NIL nodes) are black. No two red nodes can be adjacent. Every path from a node to its descendant leaves has the same number of black nodes (Black Height).Insertion Process: 123456789
Let's visualize what happens when we insert the numbers 1 through 9 into an initially empty Red-Black Tree (RB Tree), adhering to the properties mentioned above:
Inserting 1
Initially, the RB Tree is empty. We insert the value 1 as the root node, which is black by default.
``` 1B ```Inserting 2
Next, we insert the value 2. Since 1 is black, 2 can be inserted as a right child of 1 without violating any properties.
``` 1B / 2R ```Inserting 3
Inserting 3 as the right child of 2 causes a violation of property 4 (no two consecutive red nodes). To correct this, we perform a left rotation on node 1.
``` 2B / 1R 3R ```Inserting 4
Inserting 4 as the right child of 3 again violates property 4. We perform another left rotation on node 2 to correct the issue.
``` 3B / 2R 4R / 1B ```Inserting 5
Inserting 5 as the right child of 4 again violates property 4. We perform a left rotation on node 3.
``` 4B / 3R 5R / 2B / 1B ```Inserting 6
Inserting 6 as the right child of 5 again violates property 4. We perform a left rotation on node 4.
``` 5B / 4R 6R / 3B / 2B / 1B ```Inserting 7
Inserting 7 as the right child of 6 again violates property 4. We perform a left rotation on node 5.
``` 6B / 5R 7R / 4B / 3B / 2B / 1B ```Inserting 8
Inserting 8 as the right child of 7 again violates property 4. We perform a left rotation on node 6.
``` 7B / 6R 8R / 5B / 4B / 3B / 2B / 1B ```Inserting 9
Inserting 9 as the right child of 8 again violates property 4. We perform a left rotation on node 7.
``` 8B / 7R 9R / 6B / 5B / 4B / 3B / 2B / 1B ```Finally, after inserting all values from 1 to 9, the Red-Black Tree takes the following structure:
``` 5B / 3R 7R / / 2B 6B 8B / / / 1B NIL 9R ```Conclusion
The final Red-Black Tree maintains all the properties described above. It ensures that the black heights are balanced, and no two consecutive red nodes are present.