给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
提示:
树中节点总数在范围 [0, 5000] 内
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
先看提示,范围5后面6个零,是小于int的
解法一
class Solution {
List> ret = new linkedList>();
Deque path = new linkedList();
public List> pathSum(TreeNode root, int targetSum) {
dfs(root, targetSum);
return ret;
}
public void dfs(TreeNode root, int targetSum) {
if (root == null) {
return;
}
path.offerLast(root.val);
//这里不能换为 path.push(root.val);
targetSum -= root.val;
if (root.left == null && root.right == null && targetSum == 0) {
ret.add(new linkedList(path));
}
dfs(root.left, targetSum);
dfs(root.right, targetSum);
path.pollLast();
//这里不能换为path.pop();
}
}
offerLast和push有什么区别
首先daque是一个队列(逻辑上可以想象为一个双向栈)
offerLast和pollLast是在队列的后面添加删除元素
push和pop是在队列的前面添加删除元素
这题如果改成push和pop,本是5,4,11,2的路径会变成2,11,4,5
解法二
class Solution {
private List list = new ArrayList<>();
private List> res = new ArrayList<>();
public List> pathSum(TreeNode root, int targetSum) {
if (root == null) {
return res;
}
list.add(root.val);
if (root.left == null && root.right == null && root.val == targetSum) {
res.add(new ArrayList<>(list));
}
pathSum(root.left, targetSum - root.val);
pathSum(root.right, targetSum - root.val);
list.remove(list.size() - 1);
return res;
}
}
这说明add和remove是在队列后面进行操作
(remove指定了位置)



