class Solution {
List<List> res = new ArrayList();
List path = new ArrayList();
public List<List> pathTarget(TreeNode root, int target) {
dfs(root, target, 0);
return res;
}
void dfs(TreeNode root, int target, int cur){
if(root == null) return;
path.add(root.val);
cur += root.val;
if(root.left == null && root.right == null && cur == target){
res.add(new ArrayList(path));
}
dfs(root.left, target, cur);
dfs(root.right, target, cur);
path.remove(path.size()-1);
cur -= root.val;
}
共以下 8 个回答
解题思路 sumList)。一定要想清楚,当前的next和sum,sumList是什么状态进来的?
– 使用递归进行回溯(就是下一步进行不同的选择,比如当前节点的下一步是左子树还是右子树)
– 关键在于设计dfs函数的定义。dfs(TreeNode next, int sum, List
– 应该是sum还没有加next的值,sum是sumList的值之和
【题解1】dfs,自己的解法,还有改进空间
【题解2】dfs,参考的题解,这个写法节约了一些内存空间
思路: 回溯
有一两个需要注意的点
1. 不能直接添加path到结果数组,因为java中数组名是一个引用,要复制一个集合加入result
2. 结束条件不是target=0而是target=root.val
优先深度搜索。
时间复杂度O(N),空间复杂度O(N)。
//先序遍历二叉树+回溯记录路径
class Solution {> res = new LinkedList<>(); path = new LinkedList<>(); > pathTarget(TreeNode root, int target) {
LinkedList<List
LinkedList
public List<List
recur(root, target);
return res;
}
void recur(TreeNode root, int tar) {
if(root null) return;
path.add(root.val);
tar -= root.val;
if(tar 0 && root.left null && root.right null)
res.add(new LinkedList(path));
recur(root.left, tar);
recur(root.right, tar);
path.removeLast();
}
}
class Solution {> res = new ArrayList(); path = new ArrayList(); > pathTarget(TreeNode root, int target) {
List<List
List
public List<List
dfs(root, target, 0);
return res;
}
}
时间:O(n)
空间:O(n)
时间o(n)n是二叉树的节点个数
空间o(n)
注意点:明确函数定义:进入函数时,oneres已经包含了root节点,且root->val已经记入sum!
明确了再写