Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- bool isCousins(TreeNode* root, int x, int y) {
- int x1 = 0, y1= 0;
- int x1p, y1p;
- queue<pair<TreeNode*, int>> q ; //To store current node and its parent value
- q.push({root,-1});
- while(q.size()!=0){
- int n = q.size();
- for(int i = 0; i<n; i++){
- TreeNode * temp = q.front().first;
- int parent = q.front().second;
- q.pop();
- if(temp->val==x){
- x1 = x;
- x1p = parent;
- }
- if(temp->val==y){
- y1 = y;
- y1p= parent;
- }
- if(temp->left!=NULL){
- q.push({temp->left, temp->val});
- }
- if(temp->right!=NULL){
- q.push({temp->right, temp->val});
- }
- }
- if((x1!=0 && y1==0) || (x1==0 && y1!=0))return false;
- if(x1!=0 && y1!=0 && x1p!=y1p)return true;
- }
- return false;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement