Tuesday, November 3, 2015

[leetcode]Path Sum II

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        pathSumRec(root, sum, new ArrayList<Integer>());
        return result;
    }
    private void pathSumRec(TreeNode root, int sum, List<Integer> list){
        if (root == null) return;
        if (sum == root.val && root.left == null && root.right == null){
            List<Integer> temp = new ArrayList<Integer>(list);
            temp.add(root.val);
            result.add(temp);
            return;
        }
        list.add(root.val);
        pathSumRec(root.left, sum-root.val, list);
        pathSumRec(root.right, sum-root.val, list);
        list.remove(list.size()-1);
    }
}

No comments:

Post a Comment