Cousins in Binary Tree (LeetCode 993): Solution and Explanation
You get a binary tree with distinct values and two values x and y. Return true if their nodes are cousins, meaning they sit at the same depth but hang from different parents.
Intuition
Being cousins is two conditions at once: the same depth, and different parents. A level-order traversal handles the first condition for free, because every node it scans in one round has the same depth.
So scan one level at a time and note whether x and y showed up. If both appear in the same round, the depths match. If only one appears, the other must be deeper or shallower, and the answer is already false.
That leaves the parent check. Two nodes on the same level share a parent only when they are the two children of one node. So while scanning a node, look at its children: if they are exactly x and y, they are siblings and the answer is false.
Approach: Level-order BFS with a sibling check
- Start a queue with the root.
- For each level, reset
found_xandfound_y, then process exactly the nodes currently in the queue. - For each node, set
found_xorfound_yif its value matches. If its left and right children are x and y in either order, return false. - Enqueue the node's children for the next level.
- After the level: if both flags are set return true; if only one is set return false; otherwise move to the next level.
Step-by-step example
root = [1,2,3,4], x = 4, y = 3
- Depth 0: scan 1. It is neither 4 nor 3, and its children 2 and 3 are not the pair {4, 3}. Queue 2 and 3.
- Depth 1: scan 2, which queues its child 4. Scan 3: found_y becomes true.
- The level ends with found_y true and found_x false. 3 is at depth 1 but 4 is not on this level.
- The depths differ, so return false.
Code: Python, Java, C++
1class Solution:
2 def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
3 queue = collections.deque([root])
4 while queue:
5 found_x = found_y = False
6 for _ in range(len(queue)):
7 node = queue.popleft()
8 if node.val == x: found_x = True
9 if node.val == y: found_y = True
10 if node.left and node.right:
11 if {node.left.val, node.right.val} == {x, y}:
12 return False
13 if node.left: queue.append(node.left)
14 if node.right: queue.append(node.right)
15 if found_x and found_y:
16 return True
17 if found_x or found_y:
18 return False
19 return False1class Solution {
2 public boolean isCousins(TreeNode root, int x, int y) {
3 Queue<TreeNode> queue = new LinkedList<>();
4 queue.offer(root);
5 while (!queue.isEmpty()) {
6 boolean foundX = false, foundY = false;
7 for (int size = queue.size(); size > 0; size--) {
8 TreeNode node = queue.poll();
9 if (node.val == x) foundX = true;
10 if (node.val == y) foundY = true;
11 if (node.left != null && node.right != null) {
12 int a = node.left.val, b = node.right.val;
13 if ((a == x && b == y) || (a == y && b == x)) return false;
14 }
15 if (node.left != null) queue.offer(node.left);
16 if (node.right != null) queue.offer(node.right);
17 }
18 if (foundX && foundY) return true;
19 if (foundX || foundY) return false;
20 }
21 return false;
22 }
23}1class Solution {
2public:
3 bool isCousins(TreeNode* root, int x, int y) {
4 queue<TreeNode*> q;
5 q.push(root);
6 while (!q.empty()) {
7 bool foundX = false, foundY = false;
8 for (int size = q.size(); size > 0; size--) {
9 TreeNode* node = q.front();
10 q.pop();
11 if (node->val == x) foundX = true;
12 if (node->val == y) foundY = true;
13 if (node->left && node->right) {
14 int a = node->left->val, b = node->right->val;
15 if ((a == x && b == y) || (a == y && b == x)) return false;
16 }
17 if (node->left) q.push(node->left);
18 if (node->right) q.push(node->right);
19 }
20 if (foundX && foundY) return true;
21 if (foundX || foundY) return false;
22 }
23 return false;
24 }
25};Time and space complexity
O(n)
Each node is dequeued and examined once, with constant work for the value and sibling checks.
O(n)
The queue holds one level at a time, which is at most about half the nodes in a full tree.
Other approaches
DFS recording depth and parent (time O(n), space O(h))
Run one DFS that records the depth and parent of x and of y, then compare: equal depths and different parents means cousins.
BFS with (node, parent) pairs (time O(n), space O(n))
Store each node with its parent in the queue. When both values appear on one level, compare the stored parents instead of checking children.
Common mistakes
- Checking only the depth. Two nodes with the same parent are on the same level too, but they are siblings, not cousins.
- Comparing parent values from the wrong level. Reset the found flags at the start of every level.
- Returning true as soon as one value is found. You have to finish the level and confirm the other value is on it.
- Forgetting that x or y may be the root, which has no parent and no cousin.
Frequently asked questions
Why is checking a node's two children enough to rule out siblings?
Siblings are exactly two nodes that share a parent. If x and y share a parent, that parent's left and right children are x and y, which the check catches.
Can I stop the BFS early?
Yes. The first level that contains x or y decides the answer, so the loop returns at the end of that level and never scans deeper.
Does the order of x and y matter?
No. The sibling check compares the children against the pair in both orders, and the depth check is symmetric.