1 class Solution
2 {
3 public:
4 bool judge(TreeNode* root, int x, int y)
5 {
6 if(root!=NULL)
7 {
8
9 if(root->left&&root->right)
10 if((root->left->val==x&&root->right->val==y)
11 ||(root->left->val==y&&root->right->val==x))
12 {
13 return false;
14 }
15 if(!judge(root->left,x,y))
16 return false;
17 if(!judge(root->right,x,y))
18 return false;
19 }
20 return true;
21 }
22 bool isCousins(TreeNode* root, int x, int y)
23 {
24 if(!judge(root,x,y))
25 return false;
26 queue<pair<TreeNode*,int>> q;
27 q.push({root,0});
28 int rnt1,rnt2;
29 while(!q.empty())
30 {
31 pair<TreeNode*,int> t = q.front();
32 q.pop();
33 if(t.first->val==x)
34 {
35 rnt1 = t.second;
36 }
37 else if(t.first->val==y)
38 {
39 rnt2 = t.second;
40 }
41 if(t.first->left)
42 q.push({t.first->left,t.second+1});
43 if(t.first->right)
44 q.push({t.first->right,t.second+1});
45 }
46 if(rnt1==rnt2)
47 {
48 return true;
49 }
50 return false;
51 }
52 };