首页 > 其他 > 详细

113. Path Sum II

时间:2016-06-12 07:11:36      阅读:198      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!