Cousins In Binary Tree Problem
Description
LeetCode Problem 993.
Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.
Two nodes of a binary tree are cousins if they have the same depth with different parents. Note that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the 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
Constraints:
- The number of nodes in the tree is in the range [2, 100].
- 1 <= Node.val <= 100
- Each node has a unique value.
- x != y
- x and y are exist in the tree.
Solution
Approach: DFS Recording Depth and Parent
Two nodes are cousins when two facts hold: they have the same depth, and they have different parents. So all we need is the depth and the parent of x and of y, and one traversal finds both.
- Run a DFS that carries the current depth and the parent's value. The root starts at depth 0 with a placeholder parent (0 works, since node values are at least 1).
- When the node's value is
xory, record its depth and its parent's value. - Recurse into the children with
depth + 1and the current node as their parent. - Return
depth[x] == depth[y] and parent[x] != parent[y].
Both conditions are needed. Same depth alone also accepts siblings (4 and 5 in [1,2,3,4,5] share the parent 2), and different parents alone also accepts nodes at different depths. Since values are unique, a value identifies its node, so comparing parent values is the same as comparing parent nodes.
A level-by-level BFS works just as well: in each level, check whether x and y both appear, and whether they hang off the same node.
Complexity: O(n) time, where n is the number of nodes, and O(h) space for the recursion, where h is the height of the tree.
class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
depth = {} # value -> depth, for x and y
parent = {} # value -> parent value, for x and y
def dfs(node: Optional[TreeNode], node_depth: int, parent_val: int) -> None:
if node is None:
return
if node.val == x or node.val == y:
depth[node.val] = node_depth
parent[node.val] = parent_val
dfs(node.left, node_depth + 1, node.val)
dfs(node.right, node_depth + 1, node.val)
dfs(root, 0, 0) # the root has no parent; 0 is not a node value
return depth[x] == depth[y] and parent[x] != parent[y]
Now write it from memory
Close the write-up and solve it yourself against the tests.