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

Problem Path Sum II

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

标签:des   style   blog   color   strong   io   

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

标签:des   style   blog   color   strong   io   

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

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