1
bool isMinHeap(int A[],int size)
{
    for(int i=1; i<=size; i++)
    {
        if((A[i]<=A[2i]) && (A[i]<=A[2i+1]))
            t=1;
        else
        {
            t=0;
            break;
        }
    }
    if(t==1)
        return true;
    else return false;
}

I search this question in stack overflow. But the coding is difficult to understand by me as someone used recursive procedure.

I know in Min Heap every parent node is less than or eqaul to its children...i also know we represent parent in Tree[K] using formula Tree[K/2] and its left child is Tree[2K] and its right child is Tree[2K+1] and this is true only if we start our array from 1 not 0.

There are three cases to check whether my array is min heap or not:
1. Internal nodes have both left and right children.
2. The last node may have only one child which is left child.
3. Leafs do not have any child.

but i cannot understand how i can do it in the form of code in my program...plz modify my program or give me hint, how can i do that....????

Umair Mahmood
  • 63
  • 1
  • 9

1 Answers1

0

You can the code below to get the required answer. you need to iterate until you have checked all the nodes in the tree. here i'm doing this by checking that whether the loop run until size/2 or not. Suppose if array is of size i would check it for size/2= 5/2 =2 i.e (c==2) I hope it will help!

     void minheap()        
     {
    int c=0;

for(int i=1;i<=size;i++)
    {
        if(a[i]<a[i*2] && a[i]<a[i*2+1])
        {
              c++;
        }
    }
    if(c==size/2)
    {
        cout<<"Min heap";
        //return true;
    }
    else
    {
        cout<<"Not Min heap";
        //return false;
    }
}