您的位置:首页 > 其它

Path Sum II

2016-07-12 14:20 393 查看
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]

]

先记录每条路径,若碰到叶子切点,且路径之和恰好等于sum,则记录该路径,递归回退时回退该路径。

public class Solution {
List<List<Integer>> treeList =  new ArrayList<List<Integer>>();

public  void pathSumRe(TreeNode root, int sum,List<Integer> list)
{
if(root == null)
{
return;
}
int value = root.val;
list.add(value);
if((root.right ==null) && (root.left == null) && (value == sum))//叶子节点
{
treeList.add(new ArrayList<Integer>(list));
}
pathSumRe(root.right, (sum - value), list) ;
pathSumRe(root.left, (sum - value), list);
list.remove(list.size() - 1);
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<Integer> list = new ArrayList<Integer>();

pathSumRe(root, sum,list);
return treeList;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  path tree