首页 > 其他 > 详细

Problem Path Sum II

时间:2014-07-07 16:58:12      阅读:306      评论:0      收藏:0      [点我收藏+]

Problem Description: Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.

Solution: 递归。

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

 

Problem Path Sum II,布布扣,bubuko.com

Problem Path Sum II

原文:http://www.cnblogs.com/liew/p/3814993.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!