My simple java solution

  • 9
    private List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        helper(new ArrayList<Integer>(), root, sum);
        return result;
    private void helper(List<Integer> list, TreeNode root, int sum) {
        if (root == null) return;
        sum -= root.val;
        if (root.left == null && root.right == null) {
            if (sum == 0) result.add(list);
        helper(new ArrayList<Integer>(list), root.left, sum);
        helper(new ArrayList<Integer>(list), root.right, sum);

  • 0

    So each loop you would copy a new list for the next node and if the list matches target you add it to the result, right?

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.