From c6d7c78dee47ee1eded34779c53227c3f49eeef8 Mon Sep 17 00:00:00 2001 From: Chenxue3 <71321839+Chenxue3@users.noreply.github.com> Date: Tue, 16 Jan 2024 01:37:06 +1300 Subject: [PATCH] =?UTF-8?q?0112.=E8=B7=AF=E5=BE=84=E6=80=BB=E5=92=8C.md=20?= =?UTF-8?q?=E6=B7=BB=E5=8A=A00113=20=E8=B7=AF=E5=BE=84=E6=80=BB=E5=92=8CII?= =?UTF-8?q?=20C#=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0112.路径总和.md | 56 +++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 28134a7c..d45be3bd 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -1523,8 +1523,64 @@ public bool HasPathSum(TreeNode root, int targetSum) return HasPathSum(root.left, targetSum - root.val) || HasPathSum(root.right, targetSum - root.val); } ``` +0113.路径总和: +```csharp +/* + * @lc app=leetcode id=113 lang=csharp + * 0113.路径总和 II + * [113] Path Sum II + * 递归法 + */ +public class Solution { + private List> result = new List>(); + private List path = new List(); + // Main function to find paths with the given sum + public IList> PathSum(TreeNode root, int targetSum) { + result.Clear(); + path.Clear(); + if (root == null) return result.Select(list => list as IList).ToList(); + path.Add(root.val); // Add the root node to the path + traversal(root, targetSum - root.val); // Start the traversal + return result.Select(list => list as IList).ToList(); + } + + // Recursive function to traverse the tree and find paths + private void traversal(TreeNode node, int count) { + // If a leaf node is reached and the target sum is achieved + if (node.left == null && node.right == null && count == 0) { + result.Add(new List(path)); // Add a copy of the path to the result + return; + } + + // If a leaf node is reached and the target sum is not achieved, or if it's not a leaf node + if (node.left == null && node.right == null) return; + + // Traverse the left subtree + if (node.left != null) { + path.Add(node.left.val); + count -= node.left.val; + traversal(node.left, count); // Recursive call + count += node.left.val; // Backtrack + path.RemoveAt(path.Count - 1); // Backtrack + } + + // Traverse the right subtree + if (node.right != null) { + path.Add(node.right.val); + count -= node.right.val; + traversal(node.right, count); // Recursive call + count += node.right.val; // Backtrack + path.RemoveAt(path.Count - 1); // Backtrack + } + } +} + +// @lc code=end + +```

+