Skip to content

Commit c356a0c

Browse files
committed
添加0113.路径总和-ii Java代码
只看到了112题的代码,补上113的
1 parent b8bb778 commit c356a0c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

problems/0112.路径总和.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,42 @@ class Solution {
347347
}
348348
```
349349

350+
0113.路径总和-ii
351+
352+
```java
353+
class Solution {
354+
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
355+
List<List<Integer>> res = new ArrayList<>();
356+
if (root == null) return res; // 非空判断
357+
358+
List<Integer> path = new LinkedList<>();
359+
preorderDFS(root, targetSum, res, path);
360+
return res;
361+
}
362+
363+
public void preorderDFS(TreeNode root, int targetSum, List<List<Integer>> res, List<Integer> path) {
364+
path.add(root.val);
365+
// 遇到了叶子节点
366+
if (root.left == null && root.right == null) {
367+
// 找到了和为 targetSum 的路径
368+
if (targetSum - root.val == 0) {
369+
res.add(new ArrayList<>(path));
370+
}
371+
return; // 如果和不为 targetSum,返回
372+
}
373+
374+
if (root.left != null) {
375+
preorderDFS(root.left, targetSum - root.val, res, path);
376+
path.remove(path.size() - 1); // 回溯
377+
}
378+
if (root.right != null) {
379+
preorderDFS(root.right, targetSum - root.val, res, path);
380+
path.remove(path.size() - 1); // 回溯
381+
}
382+
}
383+
}
384+
```
385+
350386
Python:
351387

352388
0112.路径总和

0 commit comments

Comments
 (0)