Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if array is a min heap?

I have the following array. How can I check whether the array containing n elements is a min heap? enter image description here

like image 851
BeLambda Avatar asked Jul 28 '16 03:07

BeLambda


People also ask

How do you check if a given array represents a max-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).

Which of the following array are in a min heap?

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.


1 Answers

Since your index starts from 1, (index 0 contains 0 - why?), you can determine the index of a given node's children as follows:

  • Let the index of the given node be i
  • Index of i's left child: 2i
  • Index of i's right child: 2i + 1

Thus for each node, you can easily check that both children are greater than the node itself.

like image 101
wookie919 Avatar answered Sep 27 '22 20:09

wookie919