Problem Description
A binary tree with unique values is provided along with two distinct values, x and y. You must determine whether the nodes corresponding to x and y are cousins, meaning they are on the same level (depth) in the tree but have different parents.
Key Insights
- Cousins are defined by being at the same depth in the tree but having different parent nodes.
- Breadth-first search (BFS) is a natural choice as it processes nodes level by level.
- During a level traversal, record the parent of each target node (x and y).
- If both nodes are discovered in the same level and have different parents, then they are cousins.
- If only one node is found in a level, or if both are found but share the same parent, they are not cousins.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes, since every node may be visited once. Space Complexity: O(n), for storing nodes in the queue during BFS (or recursion stack in DFS in the worst case).
Solution
We use a BFS approach to traverse the tree level-by-level. For each level:
- Process all nodes and record the parent for x and y if found.
- If both x and y are found in the same level, check if their parents are different. If so, return true.
- If only one is found in the current level, the nodes do not reside at the same depth, so return false. This level-by-level checking ensures that the depth condition is met while verifying the parent condition.
Code Solutions
Below are implementations in Python, JavaScript, C++, and Java.