Check if two Nodes are Cousins | Practice | GeeksforGeeks

Given the binary Tree of and two-node values. Check whether the two-node values are cousins of each other or not.
Example 1:
Input:
      1
    /   \
   2     3
a = 2, b = 3
Output: 0


Example 2:
Input:
       1
     /   \ 
    2     3
   /       \
  5         4 
a = 5, b = 4
Output: 1
Explanation: Here, nodes 5 and 4 are
at the same level and have different
parent nodes. Hence, they both are cousins 

Your Task:
You don't need to read input or print anything. Your task is to complete the function isCousins() that takes the root node of the tree (having all nodes distinct), and two integers 'a' and 'b' as inputs. It returns true if the nodes with given values 'a' and 'b' are Cousins of each other and returns false otherwise. 
Two nodes value are cousins of each other if they are at the same level and have different parents. (The driver code will print 1 if the returned values is true,otherwise 0.)
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
1<=Number of Nodes<=1000

Note: The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
0
somyadebsarkar3633 weeks ago
pair<int,int> solve(Node* root,int n,int level){   if(root==NULL){       return make_pair(0,0);   }   if(root->data==n){       return make_pair(n,level);   }   pair<int,int> left=solve(root->left,n,level+1);   pair<int,int> right=solve(root->right,n,level+1);   if(left.first ==n){       return make_pair(root->data,left.second);   }   else if(right.first==n){       return make_pair(root->data,right.second);   }   else if(left.first!=0){       return left;       }   else if(right.first!=0){       return right;       }   return make_pair(0,0);   }
bool isCousins(Node *root, int a, int b){  //add code here.  pair<int,int> fir=solve(root,a,0);  pair<int,int> sec=solve(root,b,0);  if(fir.first!=sec.first && fir.second==sec.second){      return true;  }  return false;}
0
amanpandey30071 month ago
bool isCousins(Node *root, int a, int b){  queue<Node*>q;  q.push(root);    int f1=0,f2=0;    while(!q.empty())  {      int k=q.size();      while(k--)      {          Node*t=q.front();          q.pop();                    if(t->left and t->right)          {              if(t->left->data==a and t->right->data==b)              return false;                            if(t->left->data==b and t->right->data==a)              return false;          }                    if(t->data==a)          f1=1;                    if(t->data==b)          f2=1;                    if(t->left)          q.push(t->left);                    if(t->right)          q.push(t->right);      }            if( f1 and f2)      return true;            if(f1 || f2)      return false;  }    return false;}
+1
satyamagarwal2491 month ago
def isCousin(root, a, b):
    l[0], l[1],p[0],p[1] = None,None,None,None
    
    if root is None:
        return False
    util(root,a,b,0)
    if l[0] is not None and l[0] == l[1] and p[0] != p[1]:
        return True
    return False
        

def util(root,a,b,level):
    if root is None:
        return
    if root.left and root.left.data == a:
        l[0] = level
        p[0] = root.data
    elif root.left and root.left.data == b:
        l[1] = level
        p[1] = root.data
    if root.right and root.right.data == a:
        l[0] = level
        p[0] = root.data
    elif root.right and root.right.data == b:
        l[1] = level
        p[1] = root.data
    util(root.left,a,b,level+1) 
    util(root.right,a,b,level+1) 

l=[None] * 2 # level
p=[None] * 2 # parent

0
tarun2002ts0211 month ago
my logic - bfs code
 
bool isCousins(Node *root, int a, int b){  //add code here.  if(root->data==a||root->data==b||a==b)  return false;  int la=0,lb=0,lev=0;  Node*pra=NULL,*prb=NULL;  queue<Node*>q;  q.push(root);  while(!q.empty())  {      int s=q.size();lev++;      while(s--)      {          Node* temp1=q.front();q.pop();         if(temp1->left)         {             q.push(temp1->left);               if(temp1->left->data==a)               {la=lev;pra=temp1;}                else if(temp1->left->data==b)                {lb=lev;prb=temp1;}         }         if(temp1->right)         {             q.push(temp1->right);              if(temp1->right->data==a)               {la=lev;pra=temp1;}                else if(temp1->right->data==b)                {lb=lev;prb=temp1;}         }              }  }  if(la==lb && pra!=prb)  return true;  return false;}
0
kaditya73221 month ago

class Solution {
   
   // Returns true if the nodes with values 'a' and 'b' are cousins. Else returns false
   public boolean isCousins(Node root, int A, int B) {
       
       if(A == B) return false;
       
       if (root == null) return false;
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
 int size = queue.size();
 boolean isAexist = false;  
 boolean isBexist = false;  
 for (int i = 0; i < size; i++) {
  Node cur = queue.poll();
           if (cur.data == A) isAexist = true;
           if (cur.data == B) isBexist = true;
  if (cur.left != null && cur.right != null) { 
   if (cur.left.data == A && cur.right.data == B) { 
    return false;
   }
   if (cur.left.data == B && cur.right.data == A) { 
    return false;
   }
  }
  if (cur.left != null) {
   queue.offer(cur.left);
  }
  if (cur.right != null) {
   queue.offer(cur.right);
  }
 }
 if (isAexist && isBexist)  return true;
}
return false;
       
       
   }
}
0
amukherjee98am3 months ago
bool isCousins(Node *root, int a, int b)
{
    //add code here.
    bool found=false;
    bool sp=false;
    if(!root)
        return false;
    queue<Node*> q;
    q.push(root);
    while(!q.empty())
    {
        int n=q.size();
        while(n--)
        {
            Node* temp=q.front();
            q.pop();
            if(temp->left)
            {
                q.push(temp->left);
                if(temp->left->data==a || temp->left->data==b)
                {
                    if(found && !sp)
                        return true;
                    found=true; //found in the same level
                    sp=true; //If its the left child then there is a chance that right one matches with the other value. So same parent is true
                }
            }
            if(temp->right)
            {
                q.push(temp->right);
                if(temp->right->data==a || temp->right->data==b)
                {
                    if(found && !sp)
                        return true;
                    found=true;
                }
                if(temp->right->data!=a && temp->right->data!=b)
                {
                    sp=false; //making the same parent false
                }
            }
            sp=false;
        }
        if(found)
            return false; //If one element is found but the other one is not in a level then they can't be cousin
    }
    
}
0
17vineet3 months ago
bool isCousins(Node *root, int a, int b)
{
    Node* parent1;Node* parent2 ;
    int level1,level2 ;
    int level = 0 ;
    queue<Node*> q ;
    q.push(root) ;
    while(1)
    {
        int size = q.size() ;
        if(size==0)
            break ;
        while(size>0)
        {
            Node* node = q.front() ;
            q.pop() ;
            if(node->left)
            {
                if(node->left->data==a)
                {
                    parent1 = node ;
                    level1 = level ;
                }
                else if(node->left->data==b)
                {
                    parent2 = node ;
                    level2 = level ;
                }
                  q.push(node->left) ;
            }
            if(node->right)
            {
                if(node->right->data==a)
                {
                    parent1 = node ;
                    level1 = level ;
                }
                else if(node->right->data==b)
                {
                    parent2 = node ;
                    level2 = level ;
                }
                q.push(node->right) ;
            }
            size-- ;
        }
        level++ ;
    }
    if(level1 == level2)
        if(parent1 == parent2)
            return false ;
        else
            return true ;
    return false ;
}
+1
hrithikraina20013 months ago
C++ easy level order traversal solution
bool isCousins(Node *root, int a, int b)
{
    queue<Node* >q;
    
    if(root==NULL)
    {
        return 0;
    }
    q.push(root);
    
    while(!q.empty())
    {
        int n= q.size();
        bool aexist=false;
        bool bexist=false;
        for(int i=0;i<n;i++)
        {
            Node *temp= q.front();
            q.pop();
            if(temp->data==a)
            {
                aexist=true;
            }
             if(temp->data==b)
            {
                bexist=true;
            }
            if(temp->left && temp->right)
            {
                 if(temp->left->data==a && temp->right->data==b)
            {
                return false;
            }
             if(temp->left->data==b && temp->right->data==a)
            {
                return false;
            }
            }
           
            
            if(temp->left){
                q.push(temp->left);
            }
            if(temp->right)
            {
                q.push(temp->right);
            }
        }
        if(aexist && bexist)
        {
            return 1;
        }
        
        
    }
    return 0;
   //add code here.
}
Explaination: 
1. We are using level order traversing here. So there is no need to keep check of levels of both the cousin elements.
2. Make aexist and bexist as false before traversing a particular level. If it's present, we make it true inside the program.
3. If left and right child of node is there, and left is a and right is b or left is b and right is a, then we have to return false as both have same parent.
4. at the end of the particular level traversal , we check if a and b exists there and if yes, then return 1.
0
chessnoobdj4 months ago
Easy c++
void helper(Node *root, int x, int y, vector<pair<int,int>> &res, int depth){
        if(!root)
            return;
        if(root->left && root->right){
            if(root->left->data==x && root->right->data==y)
                return;
            if(root->left->data==y && root->right->data==x)
                return;
        }
        if(root->data==x || root->data==y){
            res.push_back(make_pair(root->data, depth));
            return;
        }
        helper(root->left, x, y, res, depth-1);
        helper(root->right, x, y, res, depth-1);
    }
    
bool isCousins(Node *root, int x, int y)
{
    int depth = 0;
        vector <pair <int,int> > res;
        helper(root, x, y, res, depth);
        //for(auto i:res)
            //cout << i.first << " " << i.second << "\n";
        if(res.size() == 2 && res[0].second == res[1].second)
            return true;
        return false;
}
0
moulyapradeep5 months ago
Goldmansachs
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.