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
๐Ÿ  Family Tree Cousin Detection๐Ÿ‘ด GrandpaGeneration 0๐Ÿ‘จ Dad A๐Ÿ‘ฉ Mom BGeneration 1๐Ÿง’ Kid X๐Ÿ‘ง Kid YGeneration 2โœ… COUSINS DETECTED!๐Ÿ” Analysis:โ€ข Kid X: Generation 2, Parent = Dad Aโ€ข Kid Y: Generation 2, Parent = Mom Bโœ“ Same generationโœ“ Different parentsโ†’ They are COUSINS! ๐ŸŽ‰
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.
Asked in
Facebook 15 Amazon 12 Microsoft 8 Google 6
67.9K Views
Medium Frequency
~15 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen