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
| class Solution { public List<List<Integer>> pathSum(TreeNode root, int targetSum) { List<List<Integer>> resultList = new ArrayList<>(); List<Integer> path = new ArrayList<>(); dfs(resultList, path, root, 0, targetSum); return resultList; }
private void dfs(List<List<Integer>> resultList, List<Integer> path, TreeNode node, int sum, int targetSum) { if (node == null) { return; }
path.add(node.val); sum += node.val; if (node.left == null && node.right == null && sum == targetSum) { resultList.add(new ArrayList<>(path)); }
dfs(resultList, path, node.left, sum, targetSum); dfs(resultList, path, node.right, sum, targetSum);
path.remove(path.size() - 1); } }
|