题目描述
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
就是dfs,此处需要温习一下递归调用中全局变量或者函数参数的使用:
- 全局变量的形式,递归结束后必须对该变量修改,恢复原值;
- 函数参数的形式,因为递归调用函数时,实际上,从内存分布上看,每一层调用都保存了该层函数的参数,因此递归返回上层时,不会影响原参数值。
然后代码:
public class Solution {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
ArrayList<Integer> tmp = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null) return list;
tmp.add(root.val);
sum(root, target - root.val);
return list;
}
public void sum(TreeNode root, int target){
if(target == 0 && root.left == null && root.right == null){
list.add(new ArrayList(tmp));
}else{
if(root.left != null){
tmp.add(root.left.val);
sum(root.left, target - root.left.val);
}
if(root.right != null){
tmp.add(root.right.val);
sum(root.right, target - root.right.val);
}
}
tmp.remove(tmp.size() - 1);
}
}