Skip to content

Commit c6d7c78

Browse files
committed
0112.路径总和.md 添加0113 路径总和II C#代码
1 parent 47688ba commit c6d7c78

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

problems/0112.路径总和.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1523,8 +1523,64 @@ public bool HasPathSum(TreeNode root, int targetSum)
15231523
return HasPathSum(root.left, targetSum - root.val) || HasPathSum(root.right, targetSum - root.val);
15241524
}
15251525
```
1526+
0113.路径总和:
1527+
```csharp
1528+
/*
1529+
* @lc app=leetcode id=113 lang=csharp
1530+
* 0113.路径总和 II
1531+
* [113] Path Sum II
1532+
* 递归法
1533+
*/
1534+
public class Solution {
1535+
private List<List<int>> result = new List<List<int>>();
1536+
private List<int> path = new List<int>();
1537+
1538+
// Main function to find paths with the given sum
1539+
public IList<IList<int>> PathSum(TreeNode root, int targetSum) {
1540+
result.Clear();
1541+
path.Clear();
1542+
if (root == null) return result.Select(list => list as IList<int>).ToList();
1543+
path.Add(root.val); // Add the root node to the path
1544+
traversal(root, targetSum - root.val); // Start the traversal
1545+
return result.Select(list => list as IList<int>).ToList();
1546+
}
1547+
1548+
// Recursive function to traverse the tree and find paths
1549+
private void traversal(TreeNode node, int count) {
1550+
// If a leaf node is reached and the target sum is achieved
1551+
if (node.left == null && node.right == null && count == 0) {
1552+
result.Add(new List<int>(path)); // Add a copy of the path to the result
1553+
return;
1554+
}
1555+
1556+
// If a leaf node is reached and the target sum is not achieved, or if it's not a leaf node
1557+
if (node.left == null && node.right == null) return;
1558+
1559+
// Traverse the left subtree
1560+
if (node.left != null) {
1561+
path.Add(node.left.val);
1562+
count -= node.left.val;
1563+
traversal(node.left, count); // Recursive call
1564+
count += node.left.val; // Backtrack
1565+
path.RemoveAt(path.Count - 1); // Backtrack
1566+
}
1567+
1568+
// Traverse the right subtree
1569+
if (node.right != null) {
1570+
path.Add(node.right.val);
1571+
count -= node.right.val;
1572+
traversal(node.right, count); // Recursive call
1573+
count += node.right.val; // Backtrack
1574+
path.RemoveAt(path.Count - 1); // Backtrack
1575+
}
1576+
}
1577+
}
1578+
1579+
// @lc code=end
15261580
1581+
```
15271582
<p align="center">
15281583
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
15291584
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
15301585
</a>
1586+

0 commit comments

Comments
 (0)