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
|
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; } 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; if (s.count(x) || s.count(y)) return false; } return false; } };
|