1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
class Solution { List<List<Integer>> ans = new ArrayList<>(); List<Integer> path = new ArrayList<>(); int target;
public List<List<Integer>> pathSum(TreeNode root, int target) { this.target = target; dfs(root, 0); return ans; }
private void dfs(TreeNode root, int sum) { if (root == null) return; sum += root.val; path.add(root.val); if (sum == target && root.left == null && root.right == null) { ans.add(new ArrayList<>(path)); } dfs(root.left, sum); dfs(root.right, sum); path.remove(path.size() - 1); } }
|