Back to course home
0% completed
Vote For New Content
Cousins in Binary Tree (easy)
Problem Statement
Given the root
of a binary tree with unique
values and two different nodes x
and y
, return a boolean value based on whether the nodes corresponding to the values x
and y
are cousins.
Two nodes are cousins
if they are at the same depth
but have different parents
.
Examples
Example 1:
- Input: root = [1, 2, 3, 4, null, 5, 6], x = 4, y = 5
1
/ \
2 3
/ / \
4 5 6
- Expected Output:
true
- Justification: Nodes 4 and 5 both are at depth 2 with parent 2. They are cousins because their parents are different and they are at the same depth.
Example 2:
- Input: root = [1, 2, 3, 4, 5, null, null, null, null, 6, 7], x = 6, y = 7
1
/ \
2 3
/ \
4 5
/ \
6 7
- Expected Output:
false
- Justification: Both nodes 6 and 7 are at depth 3, but they have the same parent
5
.
Example 3:
- Input: root = [1, 2, 3, null, 4, 5, null], x = 4, y = 5
1
/ \
2 3
\ /
4 5
- Expected Output:
true
- Justification: Node 4 is at depth 2 with parent 2. Node 5 is at depth 2 with parent 3. Both nodes are at the same depth but have different parents.
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Like the course? Get enrolled and start learning!
On this page
Problem Statement
Examples
Try it yourself