Community Problem

Cousins in Binary Tree

Difficulty: Easy

Decide whether two values in a binary tree are cousins (same depth, different parents).

Cousins in Binary Tree

Decide whether two values in a binary tree are cousins (same depth, different parents).

EASY
Free
trees
binary-tree
bfs
dfs
arjunpatel

By @arjunpatel

March 14, 2026

·

Updated May 18, 2026

655 views

20

4.4 (12)

I got this on a phone screen for a senior front-end role, and the interviewer specifically wanted me to explain why BFS is the natural fit before writing code. The question was a litmus test for whether I could read "same depth, different parent" as a level-order condition rather than a path-comparison condition. The catalog covers level-order traversal, but it skipped the variant that forces you to track parents alongside depths.

Cousins in Binary Tree

In a binary tree, two nodes are cousins if they share the same depth but have different parents. The depth of the root is 0. Given the root of a binary tree and two distinct values x and y, return true if and only if the nodes with values x and y are cousins.

It is guaranteed that every value in the tree is unique, that x and y both appear in the tree, and that x != y.

Examples

Example 1:

  • Input: root = [1, 2, 3, 4], x = 4, y = 3
  • Output: false
  • Explanation: Node 4 is at depth 2 and node 3 is at depth 1. Different depths means they cannot be cousins.

Example 2:

  • Input: root = [1, 2, 3, null, 4, null, 5], x = 5, y = 4
  • Output: true
  • Explanation: Both nodes are at depth 2. Their parents are 3 and 2 respectively, so they are cousins.

Example 3:

  • Input: root = [1, 2, 3, null, 4], x = 2, y = 3
  • Output: false
  • Explanation: Same depth (1) but they share the same parent (the root), so they are siblings, not cousins.

Example 4:

  • Input: root = [1, 2, 3, 4, 5, 6, 7], x = 4, y = 7
  • Output: true
  • Explanation: Both at depth 2, parents are 2 and 3 respectively.

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 and both x and y are values in the tree.

Follow-up

Can you do it in a single BFS pass without storing parent pointers, by only tracking the parent at the time you discover each target?

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems