I have the following array. How can I check whether the array containing n elements is a min heap?
An Efficient Solution is to compare root only with its children (not all descendants), if root is greater than its children and the same is true for all nodes, then tree is max-heap (This conclusion is based on transitive property of > operator, i.e., if x > y and y > z, then x > z).
7. Which one of the following array elements represents a binary min heap? Explanation: A tree is min heap when data at every node in the tree is smaller than or equal to it's children' s data. So, only 8 10 12 25 14 17 generates required tree.
Since your index starts from 1, (index 0 contains 0 - why?), you can determine the index of a given node's children as follows:
i
i
's left child: 2i
i
's right child: 2i + 1
Thus for each node, you can easily check that both children are greater than the node itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With