993. Cousins in Binary Tree LeetCode Solution
In this guide, you will get 993. Cousins in Binary Tree LeetCode Solution with the best time and space complexity. The solution to Cousins in Binary Tree problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Cousins in Binary Tree solution in C++
- Cousins in Binary Tree solution in Java
- Cousins in Binary Tree solution in Python
- Additional Resources

Problem Statement of Cousins in Binary Tree
Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.
Two nodes of a binary tree are cousins if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1.
Example 1:
Input: root = [1,2,3,4], x = 4, y = 3
Output: false
Example 2:
Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true
Example 3:
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false
Constraints:
The number of nodes in the tree is in the range [2, 100].
1 <= Node.val <= 100
Each node has a unique value.
x != y
x and y are exist in the tree.
Complexity Analysis
- Time Complexity:
- Space Complexity:
993. Cousins in Binary Tree LeetCode Solution in C++
class Solution {
public:
bool isCousins(TreeNode* root, int x, int y) {
if (root == nullptr)
return false;
queue<TreeNode*> queue{{root}};
while (!queue.empty()) {
bool isFindX = false;
bool isFindY = false;
for (int i = queue.size(); i > 0; --i) {
root = queue.front(), queue.pop();
if (root->val == x)
isFindX = true;
else if (root->val == y)
isFindY = true;
else if (root->left && root->right) {
if (root->left->val == x && root->right->val == y)
return false;
if (root->left->val == y && root->right->val == x)
return false;
}
if (root->left)
queue.push(root->left);
if (root->right)
queue.push(root->right);
}
if (isFindX && isFindY)
return true;
else if (isFindX || isFindY)
return false;
}
return false;
}
};
/* code provided by PROGIEZ */
993. Cousins in Binary Tree LeetCode Solution in Java
N/A
// code provided by PROGIEZ
993. Cousins in Binary Tree LeetCode Solution in Python
N/A
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.