diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 5ecdf350..38dd2df3 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -347,6 +347,42 @@ class Solution { } ``` +0113.路径总和-ii + +```java +class Solution { + public List> pathSum(TreeNode root, int targetSum) { + List> res = new ArrayList<>(); + if (root == null) return res; // 非空判断 + + List path = new LinkedList<>(); + preorderDFS(root, targetSum, res, path); + return res; + } + + public void preorderDFS(TreeNode root, int targetSum, List> res, List 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.路径总和