链接:
https://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca
来源:牛客网
来源:牛客网
public class Solution {
private ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();//保存所有路径
private ArrayList<Integer> list = new ArrayList<Integer>();//保存单条路径
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null) return listAll;
list.add(root.val);
target -= root.val;
if(target == 0 && root.left == null && root.right == null)
listAll.add(new ArrayList<Integer>(list));//不重新new的话从始至终listAll中所有引用都指向了同一个一个list
FindPath(root.left, target);
FindPath(root.right, target);
list.remove(list.size()-1);
return listAll;
}
}