last step uses backtracking...
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
helper(root, sum, res, new ArrayList<>());
return res;
}
private void helper(TreeNode root, int sum, List<List<Integer>> res, List<Integer> tmp) {
if (root == null) {
return;
}
tmp.add(root.val);
if (root.left == null && root.right == null && sum == root.val) { // terminator
res.add(new ArrayList<>(tmp));
}
helper(root.left, sum - root.val, res, tmp); // drill down
helper(root.right, sum - root.val, res, tmp); // drill down
tmp.remove(tmp.size() - 1); // like backtracking,
}
}