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
- 36 lines of Java from the credited upstream file 2641.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 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 public TreeNode replaceValueInTree(TreeNode root) {3 List<Integer> levelSums = new ArrayList<>();4 dfs(root, 0, levelSums);5 return replace(root, 0, new TreeNode(0), levelSums);6 }7 8 private void dfs(TreeNode root, int level, List<Integer> levelSums) {9 if (root == null)10 return;11 if (levelSums.size() == level)12 levelSums.add(0);13 levelSums.set(level, levelSums.get(level) + root.val);14 dfs(root.left, level + 1, levelSums);15 dfs(root.right, level + 1, levelSums);16 }17 18 private TreeNode replace(TreeNode root, int level, TreeNode curr, List<Integer> levelSums) {19 final int nextLevel = level + 1;20 final int nextLevelCousinsSum = nextLevel >= levelSums.size()21 ? 022 : levelSums.get(nextLevel) -23 (root.left == null ? 0 : root.left.val) -24 (root.right == null ? 0 : root.right.val);25 if (root.left != null) {26 curr.left = new TreeNode(nextLevelCousinsSum);27 replace(root.left, level + 1, curr.left, levelSums);28 }29 if (root.right != null) {30 curr.right = new TreeNode(nextLevelCousinsSum);31 replace(root.right, level + 1, curr.right, levelSums);32 }33 return curr;34 }35}36