-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path993.cpp
More file actions
33 lines (33 loc) · 744 Bytes
/
993.cpp
File metadata and controls
33 lines (33 loc) · 744 Bytes
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
/**
* 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 { // Runtime: 0 ms
public:
bool isCousins(TreeNode *root, int x, int y) {
queue<TreeNode *> q;
q.push(root);
int found = 0;
int p[2] = {-2, -2};
while (q.size()) {
auto size = q.size();
while (size--) {
auto n = q.front();
q.pop();
if (n) {
if (n->val == x || n->val == y)
p[found++] = size;
q.push(n->left), q.push(n->right);
}
}
if (found)
return found == 2 && p[0] / 2 != p[1] / 2;
}
return false;
}
};