From c356a0c92026e8e3e9f941193377cc2261793128 Mon Sep 17 00:00:00 2001 From: hk27xing <244798299@qq.com> Date: Sun, 23 May 2021 23:04:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00113.=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E6=80=BB=E5=92=8C-ii=20Java=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 只看到了112题的代码,补上113的 --- problems/0112.路径总和.md | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) 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.路径总和