剑指Offer刷题 二叉树中和为某一值的路径
原创
©著作权归作者所有:来自51CTO博客作者wx63c7a44ea77e8的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目描述
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路:


public class Solution {
private ArrayList<ArrayList<Integer>> pathList = new ArrayList<>();
private ArrayList<Integer> path = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
helpFindPath(root,target);
return pathList;
}
public void helpFindPath(TreeNode root,int restPath){
if(root==null){
return;
}
restPath-= root.val;
path.add(root.val);
if(restPath==0&&root.left==null&&root.right==null){
pathList.add(new ArrayList(path));
}
helpFindPath(root.left,restPath);
helpFindPath(root.right,restPath);
path.remove(path.size()-1);
}
}