Cousins in Binary Tree - Problem
Imagine you're at a family reunion and need to identify cousins in a family tree! Given a binary tree where each node represents a family member with a unique value, and two specific values x and y, determine if these two people are cousins.
Two nodes in a binary tree are considered cousins if they satisfy both conditions:
- They are at the same depth (same generation level)
- They have different parents (not siblings)
The root node is at depth 0, and each level down increases the depth by 1. Return true if the nodes with values x and y are cousins, false otherwise.
Example: In a family tree, if two people are at the same generation level but have different parents, they're cousins!
Input & Output
example_1.py โ Basic cousin relationship
$
Input:
root = [1,2,3,4], x = 4, y = 3
โบ
Output:
false
๐ก Note:
Nodes 4 and 3 are at different depths (4 is at depth 2, 3 is at depth 1), so they cannot be cousins.
example_2.py โ Same level, different parents
$
Input:
root = [1,2,3,null,4,null,5], x = 5, y = 4
โบ
Output:
true
๐ก Note:
Nodes 5 and 4 are both at depth 2 (same level) and have different parents (3 and 2 respectively), making them cousins.
example_3.py โ Same level, same parent (siblings)
$
Input:
root = [1,2,3,null,4], x = 2, y = 3
โบ
Output:
false
๐ก Note:
Nodes 2 and 3 are at the same depth but have the same parent (1), making them siblings, not cousins.
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 guaranteed to exist in the tree
Visualization
Tap to expand
Understanding the Visualization
1
Start at Root
Begin traversal from the family patriarch/matriarch
2
Process Each Generation
Examine all family members at each generation level
3
Track Parents
Keep record of who belongs to which family branch
4
Identify Cousins
When both targets found at same level with different parents, they're cousins!
Key Takeaway
๐ฏ Key Insight: Use BFS to process family members generation by generation, stopping as soon as both targets are found to determine their cousin relationship efficiently.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code