#993

Cousins in Binary Tree

pupil · 380 · lc easy +24 · verified · 59.1% accepted · 4,312 likes · top 56%

Description

Two nodes in a binary tree are cousins if they share the same depth but have different parent nodes.

Given the root of a binary tree with unique values and integers x and y, return true if the nodes with values x and y are cousins, or false otherwise.

Note: the root is at depth 0, and children of a depth-k node are at depth k + 1.

Example 1:

Input: root = [1,2,3,4], x = 4, y = 3
Output: false

Example 2:

Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true

Example 3:

Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false

Code

1
2
3
4
5
6
7
8
9