I am updating on the theory of algorithms (from Cormen).
There is an exercise for binary attempts in the chapter that asks:
Is it possible to use the min-heap property to print the keys of an n-node tree in sorted order in O (n) time? Show how, or explain why not.
I thought yes, it is possible.
In a mini-heap, an element in a node is smaller than its children.
Thus, the heap root is always the smallest element of all n elements, and the left child root is less than all elements in the left subtree, and the right child root is smaller than all elements in the right subtree, etc.
So, if we want to extract the root, print it, and then update the root with fewer children, we will save the min-heap property and print it in sorted order. (I am thinking of a minimal heap that is not array based).
So, this can be done in O (n) time, because to update the root we just compare 2 children and update the root pointer with the smaller of 2.
But I checked here in the solution:
Cormen Supplement Solutions
And 1) he talks about max-heaps 2) he says that this cannot be done in O (n) time:
On the heap, the node s key is both its child keys. In the binary search tree, the key node s is its left child key, but its right child key. The heap property, unlike the binary sea tree property, does not help print nodes in sorted order, because it does not indicate which subtree the node contains the element to print before that node. On the heap, the largest element is smaller than node can be in any subtree. Note that if the heap property can be used to print keys in sorting order in O (n) time, we would have an O (n) -time sorting algorithm, since building a heap takes only On Time. But we know (chapter 8) that sorting should (n lg n).
From my point of view, I can understand that using max heaps it is not possible to print them in O (n).
But is it not possible to do this using the min-heap property for the explanation I explained?
Also why the solution ignores the minimal heap. Is it a typo or a mistake?
Am I misunderstanding something?