LeetCode solutions

1035. Cousins in Binary Tree

My accepted C++ solution to LeetCode problem 1035, Cousins in Binary Tree, running in 0ms.

  • Difficulty: Easy
  • C++
  • Runtime 0ms
  • Memory 14.3MB

Read the problem on LeetCode View on GitHub

C++

Accepted on LeetCode — runtime 0ms, memory 14.3MB, accepted 2025-12-27.

cpp
class Solution {
    public:
    bool isCousins(TreeNode* root, int x, int y) {
        queue<pair<TreeNode*, TreeNode*>> q;
        q.push({root, nullptr});
        while (!q.empty()) {
            int sz = q.size();
            TreeNode *px = nullptr, *py = nullptr;
            for (int i = 0; i < sz; i++) {
                auto [node, parent] = q.front(); q.pop();
                if (node->val == x) px = parent;
                if (node->val == y) py = parent;
                if (node->left) q.push({node->left, node});
                if (node->right) q.push({node->right, node});
            }
            if (px && py) return px != py;
            if (px || py) return false;
        }
        return false;
    }
};

Source