题目
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 andsum = 22,
return
[
[5,4,11,2],
[5,8,4,5]
]
实现
定义一个结构res,保存所有路径;每个路径,用list保存;
对于叶子节点,判断从根到该叶子节点的路径和是否等于给定值,是,将list则加入到res中;
对于非叶子节点,将当前节点加入到list中,遍历左右子树;
public class path_sum_2 {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
if(root==null){
return res;
}
ArrayList<Integer> list=new ArrayList<Integer>();
pathSum(root,sum,res,list);
return res;
}
private void pathSum(TreeNode root, int sum,
ArrayList<ArrayList<Integer>> res, ArrayList<Integer> list) {
if(root==null){
return;
}
list.add(root.val);
if(root.left==null && root.right==null){
if(sum-root.val==0){
res.add(new ArrayList<Integer>(list));
}
}
pathSum(root.left,sum-root.val,res,list);
pathSum(root.right,sum-root.val,res,list);
list.remove(list.size()-1);
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}