题目
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
思路
把每次遍历的根节点存入list中
target -= root.val
如果找到,即target == 0且左右子树为空 即终止于叶节点 把路径存入result
因为递归的思想
一直递归左子树的话 到叶节点的时候
如果值不相符 返回上一层 开始递归右子树
而这时 该叶节点已经存入list
所以要删掉list中的最后一个元素
代码
public class Solution {
private ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
private ArrayList<Integer> list = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null )
return result;
list.add(root.val);
target -= root.val;
if(target == 0 && root.left == null && root.right == null)
result.add(new ArrayList<Integer>(list));
FindPath(root.left,target);
FindPath(root.right,target);
//移除最后一位元素 因为如果没有符合上述条件 说明新加入的节点值不应该在结果路径中 要删去 返回上一层
list.remove(list.size()-1);
return result;
}
}