I need to find the most efficient algorithm to merge 2 max-heaps.
Some important facts: The heaps are represented as a binary trees, that means that each node has 3 fields - value (key), pointer to right child, and pointer to left child.
My idea: to take the last leaf of the second heap and to place him as the root of the new heap. So we get a new heap, when the left child is a legal max heap, and the right child is a legal max heap. The problem (to my opinion) is only the fact that the root is not the maximal element - So we can run the function Max-Heapify from the root, and I think that it should solve the problem.
Total runtime in worst case - O(logn) - Because to make a leaf as a root is O(1), and Max-Heapify is O(logn).
What do you think about it? Am I correct? Is there more efficient algorithm to merge 2 max-heaps? (Please take in consideration the fact that the representation is binary tree)
There's two problems with your proposed approach. First is the representation: Ordinarily heaps are represented as arrays, not as individual nodes with pointers, which would require an O(n)
interleaving operation.
Even if you're fine with foregoing the array storage, though, there's the shape property to consider. Unless you're very lucky, the left and right heaps won't be the right size for the result to be a valid heap (that is, one where leaves differ in depth by at most 1, and where all the deeper leaves are on the left).
For more on merging binary heaps, see Algorithm for merging two max heaps?. However, if you're not using an array representation, not all of what's given there will necessarily apply.