/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
//对于二叉树相关的题目,只要涉及遍历,基本都可以使用递归调用的方法
//这里采用递归调用函数
//traverse--遍历的意思
//传入参数:(root,target动态) 返回:void
//终止条件:当到底的时候就终止
//内部逻辑:
// 如果到底了,并且target == 0,就说明这条路等于给定目标和,将path加入到结果,返回
// 如果到底了,但是target !=0,说明这条路不行,返回
// 如果没到底,遍历左边,即递归进入下一层,然后回溯
// 如果没到底,遍历右边,即递归进入下一层,然后回溯
// 返回
// java的垃圾回收机制会使得临时遍历最后被回收,所以传入参数不能少path和res
class Solution {
public List<Integer> path = new ArrayList<>();
public List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if(root == null) return res;
traverse(root, targetSum - root.val, path, res);
return res;
}
public void traverse(TreeNode root, int target, List<Integer> path, List<List<Integer>> res){
path.add(root.val);
if(root.left == null && root.right == null && target == 0){
System.out.println(path);
res.add(path);
System.out.println("res = "+res);
return;
}
if(root.left == null && root.right == null){
return;
}
if(root.left != null){
traverse(root.left, target- root.left.val, path, res);
path.remove(path.size()-1);
}
if(root.right != null){
traverse(root.right, target- root.right.val, path, res);
path.remove(path.size()-1);
}
return;
}
}
出现的问题:
原因很苟,我看不懂。。。
就改一行代码,就是res.add(path)
改成res.add(new ArrayList<>(path))
不过仔细看上面最后打印出两个5845大概明白是因为这个装进res数组的结果是地址型的,会随着path的值变化而变化。
- path在递归函数里面最后是得到5845。
- 最后输出5,5大概率是因为递归函数的回溯删除了后面的值,这下就懂了!