Can multiple valid left leaning red black trees exist for the same data set?

125 Views Asked by At

I have this 2-3 tree:

2-3 Tree

My teacher asked me to create a left leaning red black tree after inserting value 8.

My answer was:

My Answer to the Question

But the expected answer provided by the teacher was:

Teacher's Answer to the Question

They marked it as wrong. Although it clearly is a different tree, it looks to me this tree is still valid.

I wonder whether it is possible to have multiple valid left leaning red black trees given the same 2-3 tree. As long as the conditions of the LLRB are met, can there be multiple representations of this?

1

There are 1 best solutions below

0
trincot On

The tree you have answered with breaks the rule that the inorder traversal should result in a sorted sequence. This is not the case as 11 gets visited before 8.

Here is the procedure to come to the desired solution:

The input 2-3 tree is:

         ___(12 16)___
        /      |      \
     (2 11) (13 15) (20 22)

The insertion of 8 leads to an overflow in a leaf node:

          ___(12 16)___
         /      |      \
    (2 8 11) (13 15) (20 22)

...so it needs to split, moving the middle value up:

       __(8 12 16)______
      /    |   \        \
    (2)  (11) (13 15) (20 22)

...and now the top node overflows, so it needs to split, creating a new root node:

           __(12)__
          /        \        
       (8)        _(16)_
      /   \      /      \
    (2)  (11) (13 15) (20 22)

Finally, this 2-3 tree needs to be mapped to a left-leaning red-black tree. In this conversion 3-nodes get a red edge:

         __12__
        /      \        
       8       16
      / \     /  \
     2  11  15    22
           /R    /R
          13    20

Multiple valid LLRB trees?

Yes, there can be multiple valid LLRB trees for the same data set, but they would equally map to different 2-3 trees for the same set.

Given that you were asked to insert the value 8 in the given 2-3 tree, and the insertion of a value follows a strict algorithm, the outcome is a unique 2-3 tree, and so the corresponding LLRB tree is also uniquely defined.

There is just one correct solution to the challenge you got.