Cousins in Binary Tree

Given the root of a binary tree with unique values and the values of two different nodes x and y, return true if the nodes are cousins: they sit at the same depth but have different parents. The root is at depth 0 and the children of a node at depth k are at depth k + 1.

30:00

Cousins in Binary Tree
easy
Free written solution
Topics
Companies

Given the root of a binary tree with unique values and the values of two different nodes x and y, return true if the nodes are cousins: they sit at the same depth but have different parents. The root is at depth 0 and the children of a node at depth k are at depth k + 1.

Example 1:
Input: {"root":[1,2,3,4],"x":4,"y":3}
Output: false
Constraints:
  • The number of nodes in the tree is in the range [2,100][2, 100].

  • 1≤Node.val≤1001 \leq \text{Node.val} \leq 100

  • Each node has a unique value.

  • x≠yx \neq y

  • x and y exist in the tree.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,2,3,4],"x":4,"y":3}

Cousins share a depth but not a parent. Walk the tree one level at a time and watch for 4 and 3.

d0d1d2123y4x

x = 4

depth ?

parent ?

y = 3

depth ?

parent ?

same depth: ?
different parents: ?
this level: found_x=F found_y=F

starting at the root

Variables
VariableValue
x4
y3
depth-
node-
found_xFalse
found_yFalse
next[]
DepthFunction Call
Stack empty
0/6