993. Cousins in Binary Tree

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Cousin{
public:
int val;
int parent;
int depth;
Cousin(){
parent = -1;
}
Cousin(int val, int parent, int depth){
val = val;
parent = parent;
depth = depth;
}
};
class Solution {
public:
bool isCousins(TreeNode* root, int x, int y) {

TreeNode *a = nullptr, *b = nullptr;
int ia = -1, ib=-1,depth = 1;
Cousin *coux = new Cousin(), *couy = new Cousin();
queue<TreeNode* > q({root});
while(!q.empty()){
int size = q.size();
for(int i=0;i<size;++i){
TreeNode* p= q.front();
q.pop();
if(p->left){
q.push(p->left);
if(p->left->val == x){
coux->val = x;
coux->parent= p->val;
coux->depth = depth;
}
else if(p->left->val == y){
couy->val = y;
couy->parent= p->val;
couy->depth = depth;
}
}
if(p->right){
q.push(p->right);
if(p->right->val == x){
coux->val = x;
coux->parent= p->val;
coux->depth = depth;
}
else if(p->right->val == y){
couy->val = y;
couy->parent= p->val;
couy->depth = depth;
}

}
// check
if(couy->parent!=-1 && coux->parent!=-1){
if( couy->depth == coux->depth && couy->parent!=coux->parent) return true;
else return false;
}
}
depth++;
}
// 找不到
return false;

}
};