The problem. Given the root of a binary tree with unique values, and two different values x and y, return true if their nodes are cousins: at the same depth, but with different parents.
root = [1, 2, 3, null, 4, null, 5], x = 5, y = 4 -> true
root = [1, 2, 3, 4, 5], x = 4, y = 5 -> false (siblings)
root = [1, 2, 3, 4], x = 4, y = 3 -> false (different depths)Two facts decide it: each node's depth and its parent. The approaches differ in how much they compute to get those two facts for just x and y.
Members only · free account
The rest of this lesson, with 6 more sections, 1 drawing, a dry-run simulator and code in JavaScript, Python, Java and C++, opens with a free account.
Not ready yet? The Arrays course is free to read, no account needed.
In the rest of this lesson