Leaf at same level | Practice | GeeksforGeeks

Given a Binary Tree, check if all leaves are at same level or not.
Example 1:
Input: 
            1
          /   \
         2     3

Output: 1

Explanation: 
Leaves 2 and 3 are at same level.


Example 2:
Input:
            10
          /    \
        20      30
       /  \        
     10    15

Output: 0

Explanation:
Leaves 10, 15 and 30 are not at same level.

Your Task:  
You dont need to read input or print anything. Complete the function check() which takes root node as input parameter and returns true/false depending on whether all the leaf nodes are at the same level or not.
 
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(height of tree)
 
Constraints:
1 ≤ N ≤ 10^3
0
sikandarburnwal140820 hours ago
Can anyone explain what is the problem in this code or what optimization it needed because it doesn't pass 8 conditions out of 1033 test cases:
 
bool check(Node *root)   {       if(root==nullptr) return true;       map<int,Node*> mp;       queue<pair<Node*,int>> q;       q.push({root,0});       while(q.empty()==false)       {           auto u=q.front();           q.pop();           Node*curr=u.first;           int hd=u.second;           mp[hd]=curr;           if(curr->left!=nullptr) q.push({curr->left,hd+1});           if(curr->right!=nullptr) q.push({curr->right,hd+1});       }       int level=-1;       for(auto u: mp)       {           if(u.second->left==nullptr && u.second->right==nullptr)           {               if(level==-1)                {                   level=u.first;               }               if(u.first!=level) return false;           }       }       return true;   }
0
xzqtor3 days ago
why I'm getting TLE, I think it is 0(N). Can anyone help me on this....
 
 
class Solution:   def check(self, root):       li=[]       self.helper(root,0,li)       return li[-1]          def helper(self, root, l, li):       if len(li)>1:           return       if root is None:           return              if root.left is None and root.right is None:           if len(li)==0:               li.append(l)           else:               if li[-1]!=l:                   li.append(False)       self.helper(root.left, l+1, li)       self.helper(root.right, l+1,li)
0
tirtha19025685 days ago
class Solution
{
   boolean check(Node root)
   {
    
   if(root == null) return true;
  ArrayList<Integer>list = new ArrayList<>();
  Queue<Node>q = new LinkedList<>();
  q.add(root);
  int level = 0;
  while(!q.isEmpty()){
      int n = q.size();
      
      while(n-- >0){
          Node curr = q.poll();
          
          if(curr.left == null && curr.right == null){
              list.add(level);
          }
          if(curr.left != null){
              q.add(curr.left);
          }
          if(curr.right!=null){
              q.add(curr.right);
          }
      }
      
      // Incrementing level 
      level++;
  
  }
  
  // check if all the levels are same
  int temp = list.get(0);
  for(int i=0;i<list.size();i++){
      if(list.get(i) != temp){
          return false;
      }
  }
   
  return true;
  
   }
}

0
adityakapoorr0561 week ago

class Solution{
  public:
    /*You are required to complete this method*/
    int height=-1;
    bool ans;
    void rec(Node *root,int level)
    {
        if(!root||!ans)return ;
        if(!root->left&&!root->right){
            if(height==-1)height=level;
            else if(height!=level)ans=false;
            return ;
        }
        rec(root->left,level+1);
        rec(root->right,level+1);
    }
    bool check(Node *root)
    {
        ans=true;
        rec(root,0);
        return ans;
        //Your code here
    }
};
0
keshavkjha19992 weeks ago
Simple and Easy C++
bool check(Node *root){
        //Your code here
        bool isSameLevel = true;
        int level = 0;
        queue<pair<Node*, int>> q;
        q.push(make_pair(root, 0));
        while(!q.empty()){
            auto itr = q.front();
            q.pop();
            Node *currentNode = itr.first;
            if(level!=0 && itr.second!=level){
                return false;
            } else if(level==0){
                if(!currentNode->left&&!currentNode->right){
                    level = itr.second;
                }
            }
            if(currentNode->left){
                q.push(make_pair(currentNode->left, itr.second+1));
            }
            if(currentNode->right){
                q.push(make_pair(currentNode->right, itr.second+1));
            }
        }
        return isSameLevel;
    }
0
amarrajsmart1972 weeks ago
 C++ Solution :-Using Recursion.
int height(Node *root)   {       if(!root)       {           return -1;       }       return 1+max(height(root->left),height(root->right));   }   bool check(Node *root)   {       //Your code here       if(!root)       {           return 1;       }       int l=height(root->left);       int r=height(root->right);       if(l!=-1&&r!=-1)       return l==r&&check(root->left)&&check(root->right);       else if(l!=-1) return r==-1&&check(root->left);       else       return l==-1&&check(root->right);   }
+1
sachinnnnnn2 weeks ago
public:   /*You are required to complete this method*/   bool check(Node *root)   {       queue<Node*>q;       q.push(root);       int res=0;       while(!q.empty()){           int cnt=q.size();           for(int i=0;i<cnt;i++){               Node* curr=q.front();               q.pop();               if(curr->left==NULL && curr->right==NULL) res++;               if(curr->left) q.push(curr->left);               if(curr->right) q.push(curr->right);           }           if(res==cnt) return true;       }       return false;   }
+1
hrithikraina20013 weeks ago
 Total time taken: 0.3/1.6 C++ SOLUTION
    bool check(Node *root)
    { 
        if(root==NULL)
        {
            return 0;
        }
        int level=0;
        queue<Node *>q;
        
        q.push(root);
       
        set<int>x;
        while(!q.empty())
        {
            int n= q.size();
            while(n--)
            {
                Node *temp= q.front();
                q.pop();
                if(temp->left==NULL && temp->right==NULL)
                {
                    x.insert(level);
                }
                if(temp->left)
                {
                    q.push(temp->left);
                }
                if(temp->right)
                {
                    q.push(temp->right);
                }
                
            }
            level++;
            
        }
        if(x.size()>1)
        {
            return 0;
        }
       
        return 1;
        
        //Your code here
    }
+1
himanshu0719cse193 weeks ago
void helper(Node root,HashSet<Integer>set,int level)   {       if(root==null)       {           return;       }       if(root.left==null&&root.right==null)       {           set.add(level);       }       helper(root.left,set,level+1);       helper(root.right,set,level+1);   }   boolean check(Node root)   {       HashSet<Integer>set=new HashSet<>();       helper(root,set,0);       return set.size()==1?true:false;   }
0
ahmadsahil261 month ago
 
// JAVA Solution
 
class Solution{      int level = -1;         boolean solve(Node root,int l){                     if(root==null)           return true;              if(root.left==null&&root.right==null)           if(level==-1)               level = l;           else if(level!=l)               return false;              boolean left = solve(root.left,l+1);       if(left==false)           return false;       boolean right = solve(root.right,l+1);              return right;          }         boolean check(Node root)   {// Your code here            return solve(root,0);           }} 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.