码迷,mamicode.com
首页 > 其他好文 > 详细

113. Path Sum II

时间:2016-06-12 07:11:54      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

也不难,就是记得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     }

 

113. Path Sum II

标签:

原文地址:http://www.cnblogs.com/warmland/p/5576414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!