0%

993. Cousins in Binary Tree

bfs O(n) time O(n) space

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isCousins(TreeNode* root, int x, int y) {
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
unordered_set<int> s;
for (int i = q.size(); i > 0; --i) {
auto t = q.front(); q.pop();
if (t->left && t->right) {
unordered_set<int> temp{t->left->val, t->right->val};
if (temp.count(x) && temp.count(y)) return false; // 如果x和y共父,则非法
}
s.insert(t->val);
if (t->left) {
q.push(t->left);
}
if (t->right) {
q.push(t->right);
}
}
if (s.count(x) && s.count(y)) return true; // 搜集当前层所有点,看x和y是不是都存在
if (s.count(x) || s.count(y)) return false;
}
return false;
}
};