leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0993.cpp (933B)


      1 class Solution {
      2   public:
      3     bool isCousins(TreeNode *root, int x, int y) {
      4         if (!root) return {};
      5 
      6         bool fx = false, fy = false;
      7         queue<TreeNode *> q;
      8         q.push(root);
      9         for (int lvl = 0; !q.empty(); lvl++) {
     10             for (int t = q.size(); t > 0; t--) {
     11                 TreeNode *root = q.front();
     12                 q.pop();
     13                 if (root->left && root->right)
     14                     if ((root->left->val == x && root->right->val == y) ||
     15                         (root->left->val == y && root->right->val == x))
     16                         return false;
     17 
     18                 if (root->val == x) fx = true;
     19                 if (root->val == y) fy = true;
     20 
     21                 if (root->left) q.push(root->left);
     22                 if (root->right) q.push(root->right);
     23             }
     24 
     25             if (fx && fy) return true;
     26 
     27             if (fx || fy) return false;
     28         }
     29         return false;
     30     }
     31 };