Cousins in a Binary Tree

Medium

Question

Given the root of a binary tree and two of its nodes' values, return whether the nodes are cousins of each other.

Nodes are cousins if they have the same depth and different parents.

The values of the nodes in the tree are all unique.

Cousins in a Binary Tree Example 1

Input: root = [1, 2, 3, 4, 5, None, 7], a = 4, b = 7

Output: True

4 and 6 are cousins because they're at the same depth and have different parents.

Cousins in a Binary Tree Example 2

Input: root = [1, 2, 3, None, 5], a = 2, b = 3

Output: False

2 and 3 are not cousins because they have the same parents.

Cousins in a Binary Tree Example 3

Input: root = [1, 2, 3, 4], a = 3, b = 4

Output: False

3 and 4 are not cousins because they have different depths.

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

Which of these pairs of nodes is cousins for the following tree? [1, 2, 3, 4, None, None, 7]
a = 4, b = 7
a = 2, b = 7
a = 2, b = 3
a = 3, b = 4

Login or signup to save your code.

Notes