Advertisement
vaibhav1906

Cousin in tree

Jan 7th, 2022
815
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.24 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool isCousins(TreeNode* root, int x, int y) {
  4.        
  5.         int x1 = 0, y1= 0;
  6.         int x1p, y1p;
  7.         queue<pair<TreeNode*, int>> q ; //To store current node and its parent value
  8.         q.push({root,-1});
  9.        
  10.         while(q.size()!=0){
  11.            
  12.             int n = q.size();
  13.            
  14.             for(int i = 0; i<n; i++){
  15.                
  16.                 TreeNode * temp = q.front().first;
  17.                 int parent = q.front().second;
  18.                 q.pop();
  19.                
  20.                 if(temp->val==x){
  21.                     x1 = x;
  22.                     x1p = parent;
  23.                 }
  24.                 if(temp->val==y){
  25.                     y1 = y;
  26.                     y1p= parent;
  27.                 }
  28.                
  29.                 if(temp->left!=NULL){
  30.                     q.push({temp->left, temp->val});
  31.                 }
  32.                  if(temp->right!=NULL){
  33.                     q.push({temp->right, temp->val});
  34.                 }
  35.             }
  36.            
  37.             if((x1!=0 && y1==0) || (x1==0 && y1!=0))return false;
  38.             if(x1!=0 && y1!=0 && x1p!=y1p)return true;
  39.            
  40.         }
  41.        
  42.        
  43.         return false;
  44.        
  45.     }
  46. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement