113. Path Sum II

也不难,就是记得helper里调用的时候重新建一个list传入,不然传入的是指针,每个调用都修改同一个list会乱(22,23行处)

 1     public List<List<Integer>> pathSum(TreeNode root, int sum) {
 2         List<List<Integer>> res = new ArrayList<List<Integer>>();
 3         if(root == null) {
 4             return res;
 5         }
 6         helper(root, sum, 0, res, new ArrayList<Integer>());
 7         return res;
 8     }
 9     
10     private void helper(TreeNode root, int sum, int curSum, List<List<Integer>> res, List<Integer> curPath) {
11         if(root == null) {
12             return;
13         }
14         if(root.left == null && root.right == null) {
15             if(curSum + root.val == sum) {
16                 curPath.add(root.val);
17                 res.add(curPath);
18             }
19             return;
20         }
21         curPath.add(root.val);
22         helper(root.left, sum, curSum + root.val, res, new ArrayList<Integer>(curPath));
23         helper(root.right, sum, curSum + root.val, res, new ArrayList<Integer>(curPath));
24     }

 

posted @ 2016-06-12 05:09  warmland  阅读(127)  评论(0编辑  收藏  举报