Skip to content

Files

Latest commit

78c4434 · Jun 19, 2021

History

History
39 lines (33 loc) · 993 Bytes

README.md

File metadata and controls

39 lines (33 loc) · 993 Bytes

Path Sum II

Solution 1

/**
 * Question   : 113. Path Sum II
 * Complexity : Time: O(n) ; Space: O(n)
 * Topics     : Backtracking
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<Integer> path = new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        pathSumUtil(root, targetSum, path, res);
        return res;
    }

    private void pathSumUtil(TreeNode root, int targetSum, List<Integer> path, List<List<Integer>> res) {
        if (root == null) {
            return;
        }

        path.add(root.val);
        int sum = targetSum - root.val;

        if (sum == 0 && root.left == null && root.right == null) {
            res.add(new ArrayList<>(path));
        }

        pathSumUtil(root.left, sum, path, res);
        pathSumUtil(root.right, sum, path, res);
        path.remove(path.size() - 1);
    }
}