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
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
C++
Accepted on LeetCode — runtime 0ms, memory 14.3MB, accepted 2025-12-27.
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;
}
};