Check if a given Binary Tree is Heap

PROBLEM :

Given a binary tree you need to check if it follows max heap property or not.

Input:
The task is to complete the method which takes one argument, root of Binary Tree. The struct Node has a data part which stores the data, pointer to left child and pointer to right child.There are multiple test cases. For each test case, this method will be called individually.

Output:
The function should return true if property holds else false.


Constraints:
1 <=T<= 30
1 <=Number of nodes<= 100
1 <=Data of a node<= 1000

Example:

Input:
2
2
5 2 L 5 3 R
4
10 20 L 10 30 R 20 40 L 20 60 R

Output:
1
0

There are two test cases.  First case represents a tree with 3 nodes and 2 edges where root is 5, left child of 5 is 2 and right child of 5 is 3.   Second test case represents a tree with 4 edges and 5 nodes.

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*
 A binary tree node has data, pointer to left child
   and a pointer to right child
struct Node
{
    int data;
    struct Node* left;
    struct Node* right;
};
*/

/*You are required to complete this method */

bool check_complete_tree(struct Node *) ;
int size_tree(struct Node *) ;
bool check_complete(struct Node *,int ,int ) ;
bool check_heap_tree(struct Node *) ;

bool isHeap(struct Node * tree)
{
    if(tree==NULL||(tree->left==NULL&&tree->right==NULL))
        return true ;
       
    return(check_complete_tree(tree)&&check_heap_tree(tree)) ;
}

bool check_complete_tree(struct Node *root)
{
    int s ;
    s=size_tree(root) ;
   
    return check_complete(root,0,s) ;
}

int size_tree(struct Node *root)
{
    if(root==NULL)
        return 0 ;
   
    int L,R ;
    L=size_tree(root->left) ;
    R=size_tree(root->right) ;
   
    return L+R+1 ;
}

bool check_complete(struct Node *root,int k,int size)
{
    if(root==NULL)
        return true ;
   
    if(k>=size)
        return false ;
       
    return (check_complete(root->left,k*2+1,size)&&check_complete(root->right,k*2+2,size)) ;
}

bool check_heap_tree(struct Node *root)
{
    if(root->left==NULL&&root->right==NULL)
        return true ;
       
    if(root->right==NULL&&root->data>=root->left->data)
        return true ;
       
    if(root->data>=root->left->data&&root->data>=root->right->data)
        return (check_heap_tree(root->left)&&check_heap_tree(root->right)) ;
       
    return false ;  
}                                                                    

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )