Problem: Path Sum II

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

image.png

image.png

class Solution {
    List<List<Integer>> ans = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        dfs(root,targetSum,new ArrayList<>());
        return ans;
    }

    private void dfs(TreeNode root, int target,List<Integer> ls){
        if(root == null){
            return;
        }
        ls.add(root.val);

        if(target - root.val == 0 && root.left==null && root.right==null){
            if(!ls.isEmpty()) ans.add(new ArrayList<>(ls));
        }else{
            dfs(root.left,target-root.val,ls);
            dfs(root.right,target-root.val,ls);
        }
        ls.remove(ls.size()-1);
    }
}

image.png