kvway - 6 months ago 53

C++ Question

Consider the following example. I am adding random numbers to min heap and at the same time I am adding the same numbers in the same order to the max heap. So at the end those 2 heaps will have the same numbers with difference one being min heap and the second one being max heap.

Now here's the question:

If I decide to remove the maximal element from max heap, will that maximal element from max heap always at the bottom of min heap? If not, then another question is that if i want to remove that max element from min heap with swapping him with the last element of min heap, deleting the last element , would I need to ever run operation which would have to compare that switched element with his child in order to repair min heap? Or will it always be the case to compare it with parent in order to fix min heap?

Answer

By definition of a max heap, the root is always larger than it's children. However there is no specific ordering among children so left child isn't always greater than right and vice versa. The max element of max heap, which is the root, will have to be at a leaf in the min heap. We don't know which leaf, this will depend on the configuration of the elements. (ie. the order at which these elements are inserted, because usually elements are inserted to fill from leftmost to rightmost side of the tree)