113. Path Sum II

time: O(n)

space: O(h)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        //so this should do the entire taveral
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;

        helper(root, new ArrayList<>(), targetSum, res);
        return res;
    }
    private void helper(TreeNode root, List<Integer> path, int targetSum, List<List<Integer>> res) {
        if (root == null) return;
        
        path.add(root.val);
        if (root.left == null && root.right == null) {
            if (targetSum == root.val) {
                res.add(new ArrayList<>(path));
            }
        }
        helper(root.left, path, targetSum - root.val, res);
        helper(root.right, path, targetSum - root.val, res);
        path.remove(path.size() - 1);

    }
}

Last updated