题目:
给定一个二叉树和一个值 sum,请找出所有的根节点到叶子节点的节点值之和等于 sum 的路径,
例如:
给出如下的二叉树,sum=22 sum=22,
返回
[[5,4,11,2],
[5,8,9]]
确认了,二叉树的问题确实是算法上比较容易做出的问题,因为基本离不开树的遍历。。。
这道题目的思路还是比较清楚的,先序遍历,累加,记录路径,到达根节点进行比较,累加和等于 sum 的话,将该路径保存起来,否则丢弃。
但是有个需要注意的点,由于这道题目是多解的,在进行遍历的过程中可能有多个答案,因此在进行存储的时候,要以当前的路径 path 作为参数,新建一个List,为什么要新建呢,因为在进行遍历的过程中,当我们在遍历完左叶子结点的时候,无论结果如何,我们需要递归回到上一次,去判断右叶子节点是不是符合要求的,这时候我们需要的路径是回到其父节点,然后走到右节点,但是左节点已经加到 list 中了,所以在递归中的最后一步,我们需要将 list 中的该元素删掉,删掉之后 path 在层层往前返回的时候会重复执行这个操作,最终导致结果为空的了,所以需要新建。
完整代码如下:
public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
// write code here
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
ArrayList<Integer> path = new ArrayList<Integer>();
getPath(root, res, 0, sum, path);
return res;
}
public static void getPath(TreeNode root,ArrayList<ArrayList<Integer>> res,int count,int sum,ArrayList<Integer> path) {
if(root!=null) {
count += root.val;
path.add(root.val);
}else {
return;
}
if(root.left==null&&root.right==null&&count==sum) {
res.add(new ArrayList<>(path));
}
getPath(root.left, res, count, sum, path);
getPath(root.right, res, count, sum, path);
path.remove(path.size()-1);
}