1
                             20
                           /    \
                          18     19
                        /   \   /  \   
                      10    13 15   1                      
                      /\    /\ 
                     5 9   8  11

Above is the Max- Heap and it is the result after a sequence of insert and remove the maximum operations. Let's assume that the last operation was insert. What could have been the possible key for the last insert operation?

The reason why I am not sure is because the question does not state whether it has been heapify or not so it could or could not already be sorted. But then again I might be wrong.

Additional question : Is "remove the maximum operations" the same as "delete" because I have not encountered this term before and it would help clarify my confusion.

Thanks!

  • Given the heap that you've shown, "remove the maximum" means take the 20 out of the heap, move the 11 to where the 20 is, and re-heapify. – user3386109 May 02 '18 at 17:13
  • You certainly could have added the 11 last, because it would just stay where it is. OTOH, if the 13 was last, then before the 13 was added you would have had 18 - 11 - 8. When the 13 was added, it would get switched with the 11, and then stay where it is. So the 13 could be last. – user3386109 May 02 '18 at 17:29

1 Answers1

3

The way you insert into a binary heap is to place the item at the end of the heap and then sift it up through the heap to its proper place.

So if the heap you show is the heap after the last insertion operation, then at the start of that insertion, the heap must have had only 10 items. The new item was placed where the value 11 is right now.

If the item was sifted up from there, then the only positions it could possibly have been sifted to are where the numbers 13, 18, and 20 are right now. But the number inserted could not have been 20, because if it had been, then 18 would have been the root of the heap, and that would not have been valid (because 19 is larger than 18, and so 19 would have been the root).

So the only possible values that could have been inserted last are 18, 13, and 11.

Before insertion, that branch of the tree could have been:

  • [18,13]: adding the 11 would not require any swaps.
  • [18,11]: add 13 and then swap it with 11.
  • [13,11]: add 18, and then swap it up the tree with 11, and then with 13
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351