Problem 482324 · medium · Phase 04 Non-Linear Data Structures

Cousin Check

binary trees · breadth-first search · depth and parent tracking

In a binary tree whose node values are all distinct, two nodes are cousins if they are on the same depth but have different parents. Given the root and two values x and y, return True if the nodes holding x and y are cousins. If either value is absent, or if x == y, return False.

Examples

      1
     / \
    2   3
   /     \
  4       5

Input:  root = build_tree([1, 2, 3, 4, None, None, 5]), x = 4, y = 5
Output: True
Explanation: 4 and 5 are both at depth 2 with parents 2 and 3.
Input:  root = build_tree([1, 2, 3, 4, None, None, 5]), x = 2, y = 3
Output: False
Explanation: same depth but the same parent (siblings, not cousins).

Constraints

  • 0 <= number of nodes <= 2000, all values distinct
  • -10**4 <= node.val, x, y <= 10**4
  • Target complexity: O(n) time.

Goals

  • Record depth and parent for target values during one traversal
  • Combine two conditions: equal depth and different parents
  • Return False when a value is missing
Starting Python…