leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0993.cpp (933B)
0 class Solution {
1 public:
2 bool isCousins(TreeNode *root, int x, int y) {
3 if (!root) return {};
5 bool fx = false, fy = false;
6 queue<TreeNode *> q;
7 q.push(root);
8 for (int lvl = 0; !q.empty(); lvl++) {
9 for (int t = q.size(); t > 0; t--) {
10 TreeNode *root = q.front();
11 q.pop();
12 if (root->left && root->right)
13 if ((root->left->val == x && root->right->val == y) ||
14 (root->left->val == y && root->right->val == x))
15 return false;
17 if (root->val == x) fx = true;
18 if (root->val == y) fy = true;
20 if (root->left) q.push(root->left);
21 if (root->right) q.push(root->right);
22 }
24 if (fx && fy) return true;
26 if (fx || fy) return false;
27 }
28 return false;
29 }
30 };