Algorithm for checking if an Array with n-elements is a minimum heap

匆匆过客 提交于 2019-12-06 06:03:52

The Wikipedia article should help you.

Here are some questions to get you thinking about the solution:

  1. What must be true about the root of a heap, assuming the heap is a min heap?
  2. If the root of the heap satisfies the min heap property, how do you ensure that the subtrees of the root also hold the property?
  3. What if the root of the tree has no children? Is it a min heap?

I think this will work !

bool checkminheap(int arr[],root)
{
     if(root>=sizeof(arr)/sizeof(arr[0])-1)
         return 1;
     if(arr[root]>arr[2*root] || arr[root]>arr[2*root+1])  //check root is the smallest element
      return 0; 
    if(!checkminheap(arr,2*root))//check leftsubtree
      return 0;
    if(!checkminheap(arr,2*root+1))//check rightsubtree
      return 0;

     return 1;
}  

Adding a verbose solution with java generics support, it is relatively easier to follow.

public static <T extends Comparable<T>> boolean isMinHeap(T arr[], int rootIndex) {
  boolean isMaxH = true;
  int lChild = 2 * rootIndex + 1;
  int rChild = 2 * rootIndex + 2;

  // Nothing to compare here, as lChild itself is larger then arr length.
  if (lChild >= arr.length) {
    return true;
  }

  if (arr[rootIndex].compareTo(arr[lChild]) > 0) {
    return false;
  } else {
    isMaxH = isMaxH && isMinHeap(arr, lChild);
  }

  // rChild comparison not needed, return the current state of this root.
  if (rChild >= arr.length) {
    return isMaxH;
  }

  if (arr[rootIndex].compareTo(arr[rChild]) > 0) {
    return false;
  } else {
    isMaxH = isMaxH && isMinHeap(arr, rChild);
  }

  return isMaxH;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!