Leaf at same level

PROBLEM :

Given a Binary Tree, check if all leaves are at same level or not.

          12
        /    \
      5       7      
    /          \
   3            1
  Leaves are at same level

          12
        /    \
      5       7      
    /        
   3        
   Leaves are Not at same level


          12
        /  
      5            
    /   \      
   3     9
  /      /
 1      2
 Leaves are at same level

Input:
The task is to complete the method that takes one argument, root of Binary Tree and returns 1 if all leaves are at same level else returns 0

Output:
Output for each test case will be 0 if all leaves are not at same level else it will 1.

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

Example(To be used only for expected output):
Input
2
2
1 2 R 1 3 L
4
10 20 L 10 30 R 20 40 L 20 60 R

Output
1
0

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

/* The structure of the binary tree is as follows
struct Node
{
    int data;
    struct Node* left;
    struct Node* right;
};
*/

/*You are required to complete this method*/

int Height(Node *) ;
bool level(Node *,int ) ;

bool check(Node *root)
{
    if(root==NULL)
        return true ;
       
    int h ;
    h=Height(root) ;
    int i ;
    bool c=true ;
   
    for(i=0;i<h;i++)
    {
        c=level(root,i) ;
        if((i+1)!=h&&c!=true)
            return false ;
    }
    return true ;
}

int Height(Node *root)
{
    if(root==NULL)
        return 0 ;
       
    int l,r ;
    l=Height(root->left) ;
    r=Height(root->right) ;
   
    return l>r?(l+1):(r+1) ;
}

bool level(Node *root,int l)
{
    if(root==NULL)
        return true ;
       
    if(l==0)
    {
        if(root->left==NULL&&root->right==NULL)
            return false ;
        else
            return true ;
    }
   
    return level(root->left,l-1)&&level(root->right,l-1) ;
}

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

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 )