mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
添加0113.路径总和-ii Java代码
只看到了112题的代码,补上113的
This commit is contained in:
@ -347,6 +347,42 @@ class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
0113.路径总和-ii
|
||||
|
||||
```java
|
||||
class Solution {
|
||||
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
|
||||
List<List<Integer>> res = new ArrayList<>();
|
||||
if (root == null) return res; // 非空判断
|
||||
|
||||
List<Integer> path = new LinkedList<>();
|
||||
preorderDFS(root, targetSum, res, path);
|
||||
return res;
|
||||
}
|
||||
|
||||
public void preorderDFS(TreeNode root, int targetSum, List<List<Integer>> res, List<Integer> path) {
|
||||
path.add(root.val);
|
||||
// 遇到了叶子节点
|
||||
if (root.left == null && root.right == null) {
|
||||
// 找到了和为 targetSum 的路径
|
||||
if (targetSum - root.val == 0) {
|
||||
res.add(new ArrayList<>(path));
|
||||
}
|
||||
return; // 如果和不为 targetSum,返回
|
||||
}
|
||||
|
||||
if (root.left != null) {
|
||||
preorderDFS(root.left, targetSum - root.val, res, path);
|
||||
path.remove(path.size() - 1); // 回溯
|
||||
}
|
||||
if (root.right != null) {
|
||||
preorderDFS(root.right, targetSum - root.val, res, path);
|
||||
path.remove(path.size() - 1); // 回溯
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Python:
|
||||
|
||||
0112.路径总和
|
||||
|
Reference in New Issue
Block a user