题目描述:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路解析:
- 首先把根节点放入list中,然后target更新为去掉根节点值后的数字
- 判断是否是叶子节点,如果是叶子节点,并且target更新为0,此时符合要求,加入到listAll中
- 如果不是叶子节点,那就继续访问子节点。
- 访问结束需要将list中最后一个删掉,并减去当前节点的值。
代码:
public class Solution {
private ArrayList<ArrayList<Integer>> listPath = new ArrayList<ArrayList<Integer>>();
private ArrayList<Integer> list =new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if (root == null) {
return listPath;
}
list.add(root.val);//添加根节点
target -= root.val;//当前目标的值为减去根节点后的值
//如果节点为叶子节点且路径的值和目标的值相等
if (target == 0 && root.left == null && root.right == null) {
listPath.add(new ArrayList<Integer>(list));
}
//采用递归,回到父节点
FindPath(root.left, target);
FindPath(root.right, target);
//删除当前节点
list.remove(list.size() - 1);
return listPath;
}
}