Approach
Depth-first search
For Cousins in Binary Tree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 44 lines of Python from the credited upstream file cousins-in-binary-tree.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class TreeNode(object):6 def __init__(self, x):7 self.val = x8 self.left = None9 self.right = None10 11 12class Solution(object):13 def isCousins(self, root, x, y):14 """15 :type root: TreeNode16 :type x: int17 :type y: int18 :rtype: bool19 """20 def dfs(root, x, depth, parent):21 if not root:22 return False23 if root.val == x:24 return True25 depth[0] += 126 prev_parent, parent[0] = parent[0], root27 if dfs(root.left, x, depth, parent):28 return True29 parent[0] = root30 if dfs(root.right, x, depth, parent):31 return True32 parent[0] = prev_parent33 depth[0] -= 134 return False35 36 depth_x, depth_y = [0], [0]37 parent_x, parent_y = [None], [None]38 return dfs(root, x, depth_x, parent_x) and \39 dfs(root, y, depth_y, parent_y) and \40 depth_x[0] == depth_y[0] and \41 parent_x[0] != parent_y[0]42 43 44