递归
遇到路径长度的问题,可以利用扣减的方式,
返回的是一个字典,故只有遍历到叶子结点 且target扣减到0 为一个字典元素。
ArrayList中有一个 构造,可以传入 Collection接口的实现类。
public class Solution {
private ArrayList<ArrayList<Integer>> paths = new ArrayList<>();
private Stack<Integer> path = new Stack<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root ==null) return paths;
path.push(root.val);
target -= root.val;
if(target == 0 && root.left == null && root.right ==null){
paths.add(new ArrayList<Integer>(path));
}
FindPath(root.left,target);
FindPath(root.right,target);
path.pop();
return paths;
}
}
京公网安备 11010502036488号