题目描述

输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

思路:

剑指Offer刷题   二叉树中和为某一值的路径_二叉树


剑指Offer刷题   二叉树中和为某一值的路径_结点_02

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);
}
}