题目:
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
思路:
代码:
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
//result存储结果,sub存走过的路径,target是距离给定数值的距离大小
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> sub = new ArrayList<Integer>();
if(root == null){
return result;
}
return Find(root, target, sub,result);
}
public ArrayList<ArrayList<Integer>> Find(TreeNode root, int target,ArrayList<Integer> sub,ArrayList<ArrayList<Integer>> result){
target = target - root.val;
sub.add(root.val);
if(root.left == null && root.right == null){//叶子节点
if(target == 0){
新new一个ArrayList赋值给result,不能把sub赋值给result,sub一直在变
result.add(new ArrayList<Integer>(sub));
}
}
if(root.left != null){
result = Find(root.left, target, sub, result);
}
if(root.right != null){
result = Find(root.right, target,sub, result);
}
sub.remove(sub.size()-1);//将当前节点从路径上删除
return result;
}
}