Saw this question somewhere in the internet and tried to solve it. I could solve it for cases where the heap is a strictly binary tree (by repeatedly partitioning the preorder traversal) but could not figure out an algorithm when the heap is only a complete binary tree.
For eg, if 1, 2, 3, 4, 5, 6, 7
is the preorder traversal of a min-heap,
size of the heap is 7
1
is the first element in the heap (considering, the heap is represented as an array)
The next (size - 1) / 2
elements will be in the left sub-tree of 1
2, 3, 4
will be in the left sub-tree of 1
The last (size - 1) / 2
elements will be in the right-sub tree of 1
5, 6, 7
will be in the right sub-tree of 1
The complete heap can be constructed by applying this logic recursively.
The solution will work for cases like these where the heap is a strictly-binary tree
1
2 3
4 5 6 7
But apparently, this does not work in case of heap where a non-leaf element has one or no children. For eg,
1 1
2 3 2 3
4 5 6 4 5
I couldn't think of any clean algorithms that could do the same. Any solutions/suggestions will really help.
considering, the heap is represented as an array
, no, it is represented as pre-order traversal. Forget how it's stored in an array. – phant0mBut apparently, this does not work in case of heap where a non-leaf element has one or no children. I couldn't think of any clean algorithms that could do the same.
can you please give such an example so we're all talking about the same thing? – phant0m