Approach
Depth-first search
For Cousins in Binary Tree II, 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
- 33 lines of Python from the credited upstream file 2641.py.
- The implementation visibly relies on sequence storage.
- 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.
1class Solution:2 def replaceValueInTree(self, root: TreeNode | None) -> TreeNode | None:3 levelSums = []4 5 def dfs(root: TreeNode | None, level: int) -> None:6 if not root:7 return8 if len(levelSums) == level:9 levelSums.append(0)10 levelSums[level] += root.val11 dfs(root.left, level + 1)12 dfs(root.right, level + 1)13 14 def replace(15 root: TreeNode | None,16 level: int, curr: TreeNode | None,17 ) -> TreeNode | None:18 nextLevel = level + 119 nextLevelCousinsSum = (20 (levelSums[nextLevel] if nextLevel < len(levelSums) else 0) -21 (root.left.val if root.left else 0) -22 (root.right.val if root.right else 0))23 if root.left:24 curr.left = TreeNode(nextLevelCousinsSum)25 replace(root.left, level + 1, curr.left)26 if root.right:27 curr.right = TreeNode(nextLevelCousinsSum)28 replace(root.right, level + 1, curr.right)29 return curr30 31 dfs(root, 0)32 return replace(root, 0, TreeNode(0))33