添加0113.路径总和-ii Java代码

只看到了112题的代码,补上113的
This commit is contained in:
hk27xing
2021-05-23 23:04:14 +08:00
parent b8bb7786a4
commit c356a0c920

View File

@ -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 Python
0112.路径总和 0112.路径总和