113. Path Sum II

https://leetcode.com/problems/path-sum-ii/

last step uses backtracking...

why don't need to add sum back?

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, 
    }
}

Last updated