LC 113. 路径总和 II

题目描述

这是 LeetCode 上的 113. 路径总和 II ,难度为 中等

给你二叉树的根节点 root 和一个整数目标和 targetSum,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

示例 1:

1
2
3
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22

输出:[[5,4,11,2],[5,8,4,5]]

示例 2:

1
2
3
输入:root = [1,2,3], targetSum = 5

输出:[]

示例 3:
1
2
3
输入:root = [1,2], targetSum = 0

输出:[]

提示:

  • 树中节点总数在范围 $[0, 5000]$ 内
  • $-1000 <= Node.val <= 1000$
  • $-1000 <= targetSum <= 1000$

树的遍历 - DFS

定义 DFS 函数 void dfs(TreeNode root, int cur, int t, List<Integer> path)

其中 root 为当前遍历到的节点;cur 为当前路径总和;t 为目标总和;path 为当前路径方案。

剩下的为常规的树的遍历,当 root 为叶子节点(既没有左子树,也没有右子树)时,根据 cur 是否与 t 相等,决定是否要把 path 添加到答案中。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int t) {
if (root != null) dfs(root, root.val, t, new ArrayList<>(){{add(root.val);}});
return ans;
}
void dfs(TreeNode root, int cur, int t, List<Integer> path) {
if (root.left == null && root.right == null) {
if (cur == t) ans.add(new ArrayList<>(path));
return ;
}
List<TreeNode> list = new ArrayList<>();
if (root.left != null) list.add(root.left);
if (root.right != null) list.add(root.right);
for (TreeNode child : list) {
path.add(child.val);
dfs(child, cur + child.val, t, path);
path.remove(path.size() - 1);
}
}
}

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

最后

这是我们「刷穿 LeetCode」系列文章的第 No.113 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!