Cousins in Binary Tree
This problem can be solved using a depth-first search (DFS) or breadth-first search (BFS) strategy. I will solve it using DFS. Here, I use two helper functions to get the depth and parent of the given nodes.
|
|
In this code, dfs() is a helper function that performs a depth-first search through the binary tree. If it encounters a node with a value equal to x or y, it records the node’s depth and its parent. If it finds both x and y, it checks if they are at the same depth and have different parents. If they are, it sets self._isCousins to True. This value will then be returned by the isCousins() function.