min-heap order for the following

270 Views Asked by At

Consider the min-heap [13, 24, 32, 32, 41, 38, 50, 48, 40] built by repeatedly inserting values into an empty heap. Suppose the last value inserted was 24. What was the heap structure before this value was inserted?

I'm not able to figure out, what would be the answer of this

1

There are 1 best solutions below

0
trincot On

To approach this, it helps to make the visual representation of the tree:

         _ 13 _
        /      \
      24        32
     /  \      /  \
   32    41  38    50
  /  \
48    40

As 24 was inserted at the position that is currently occupied by 40 (the last entry in the array), we know the path via which this 20 had bubbled up the tree (i.e. via 32), and we can just do the inverse:

         _ 13 _
        /      \
      32        32
     /↙ \      /  \
   40    41  38    50
  / ↘\
48    24

And finally, we reverse the initial insertion of 24:

         _ 13 _
        /      \
      32        32
     /  \      /  \
   40    41  38    50
  /
48 

Write this back into array form:

[13,32,32,40,41,38,50,48]