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
Cousins in Binary Tree - BFS Approach INPUT Binary Tree Structure 1 2 3 y=3 4 x=4 Depth 0 Depth 1 Depth 2 Input Parameters: root = [1,2,3,4] x = 4, y = 3 ALGORITHM STEPS 1 Init BFS Queue Start with root node, track (node, parent, depth) 2 Level Traversal Process nodes level by level using BFS 3 Find x and y Record depth and parent for both target nodes 4 Compare Results Cousins if same depth AND different parents BFS Queue Processing: 1 2 3 4 --> FINAL RESULT Node Analysis: Node 4 (x) Depth: 2, Parent: 2 Node 3 (y) Depth: 1, Parent: 1 Comparison: Depth 2 != Depth 1 Different depths! Output: false NOT COUSINS (Different depths) Key Insight: For two nodes to be cousins, they must be at the SAME DEPTH (same generation) but have DIFFERENT PARENTS (not siblings). In this case, node 4 is at depth 2 while node 3 is at depth 1, so they cannot be cousins. BFS naturally processes nodes level by level, making depth tracking easy. TutorialsPoint - Cousins in Binary Tree | BFS Approach
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