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