|
| 1 | +### 题目描述 |
| 2 | + |
| 3 | +这是 LeetCode 上的 **[113. 路径总和 II](https://acoier.com/2022/12/10/113.%20%E8%B7%AF%E5%BE%84%E6%80%BB%E5%92%8C%20II%EF%BC%88%E4%B8%AD%E7%AD%89%EF%BC%89/)** ,难度为 **中等**。 |
| 4 | + |
| 5 | +Tag : 「DFS」、「二叉树」 |
| 6 | + |
| 7 | + |
| 8 | + |
| 9 | +给你二叉树的根节点 `root` 和一个整数目标和 `targetSum`,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。 |
| 10 | + |
| 11 | +叶子节点 是指没有子节点的节点。 |
| 12 | + |
| 13 | +示例 1: |
| 14 | + |
| 15 | + |
| 16 | +``` |
| 17 | +输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 |
| 18 | +
|
| 19 | +输出:[[5,4,11,2],[5,8,4,5]] |
| 20 | +``` |
| 21 | +示例 2: |
| 22 | + |
| 23 | +``` |
| 24 | +输入:root = [1,2,3], targetSum = 5 |
| 25 | +
|
| 26 | +输出:[] |
| 27 | +``` |
| 28 | +示例 3: |
| 29 | +``` |
| 30 | +输入:root = [1,2], targetSum = 0 |
| 31 | +
|
| 32 | +输出:[] |
| 33 | +``` |
| 34 | + |
| 35 | +提示: |
| 36 | +* 树中节点总数在范围 $[0, 5000]$ 内 |
| 37 | +* $-1000 <= Node.val <= 1000$ |
| 38 | +* $-1000 <= targetSum <= 1000$ |
| 39 | + |
| 40 | +--- |
| 41 | + |
| 42 | +### 树的遍历 - DFS |
| 43 | + |
| 44 | +定义 `DFS` 函数 `void dfs(TreeNode root, int cur, int t, List<Integer> path)` 。 |
| 45 | + |
| 46 | +其中 `root` 为当前遍历到的节点;`cur` 为当前路径总和;`t` 为目标总和;`path` 为当前路径方案。 |
| 47 | + |
| 48 | +剩下的为常规的树的遍历,当 `root` 为叶子节点(既没有左子树,也没有右子树)时,根据 `cur` 是否与 `t` 相等,决定是否要把 `path` 添加到答案中。 |
| 49 | + |
| 50 | +代码: |
| 51 | +```Java |
| 52 | +class Solution { |
| 53 | + List<List<Integer>> ans = new ArrayList<>(); |
| 54 | + public List<List<Integer>> pathSum(TreeNode root, int t) { |
| 55 | + if (root != null) dfs(root, root.val, t, new ArrayList<>(){{add(root.val);}}); |
| 56 | + return ans; |
| 57 | + } |
| 58 | + void dfs(TreeNode root, int cur, int t, List<Integer> path) { |
| 59 | + if (root.left == null && root.right == null) { |
| 60 | + if (cur == t) ans.add(new ArrayList<>(path)); |
| 61 | + return ; |
| 62 | + } |
| 63 | + List<TreeNode> list = new ArrayList<>(); |
| 64 | + if (root.left != null) list.add(root.left); |
| 65 | + if (root.right != null) list.add(root.right); |
| 66 | + for (TreeNode child : list) { |
| 67 | + path.add(child.val); |
| 68 | + dfs(child, cur + child.val, t, path); |
| 69 | + path.remove(path.size() - 1); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | +``` |
| 74 | +* 时间复杂度:$O(n)$ |
| 75 | +* 空间复杂度:$O(n)$ |
| 76 | + |
| 77 | +--- |
| 78 | + |
| 79 | +### 最后 |
| 80 | + |
| 81 | +这是我们「刷穿 LeetCode」系列文章的第 `No.113` 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。 |
| 82 | + |
| 83 | +在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。 |
| 84 | + |
| 85 | +为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode 。 |
| 86 | + |
| 87 | +在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。 |
| 88 | + |
0 commit comments