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

[leetcode]Path Sum II

时间:2014-07-31 23:17:10      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   for   ar   

Path Sum II

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

For example:
Given the below binary tree and sum = 22,

              5
             /             4   8
           /   /           11  13  4
         /  \    /         7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

 

 

算法思路:

[leetcode]Path Sum区别不大,dfs

代码如下:

 1 public class Solution {
 2     List<List<Integer>> res = new ArrayList<List<Integer>>();
 3     public List<List<Integer>> pathSum(TreeNode root, int sum) {
 4         if(root == null) return res;
 5         List<Integer> list = new ArrayList<Integer>();
 6         dfs(list, root, sum);
 7         return res;
 8     }
 9     public void dfs(List<Integer> list,TreeNode root,int sum){
10         if(root.left == null && root.right == null && root.val == sum){
11             list.add(sum);
12             res.add(new ArrayList<Integer>(list));
13             list.remove(list.size() - 1);
14             return;
15         }
16         if(root.left != null){
17             list.add(root.val);
18             dfs(list, root.left, sum - root.val);
19             list.remove(list.size() - 1);
20         }
21         if(root.right!= null){
22             list.add(root.val);
23             dfs(list, root.right, sum - root.val);
24             list.remove(list.size() - 1);
25         }
26     }
27 }

 

[leetcode]Path Sum II,布布扣,bubuko.com

[leetcode]Path Sum II

标签:style   blog   http   color   os   io   for   ar   

原文地址:http://www.cnblogs.com/huntfor/p/3883544.html

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