Skip to content

Commit e488fbd

Browse files
committed
Add Path Sum III C#
1 parent d385ad6 commit e488fbd

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
public class Solution {
2+
public int PathSum(TreeNode root, int sum) {
3+
if (root == null) {
4+
return 0;
5+
}
6+
var map = new Dictionary<int, int>();
7+
map[0] = 1;
8+
return Dfs(root, 0, sum, map);
9+
}
10+
11+
private int Dfs(TreeNode curr, int sum, int target, Dictionary<int, int> map) {
12+
if (curr == null) {
13+
return 0;
14+
}
15+
// update the prefix sum by adding the current val
16+
sum += curr.val;
17+
// get the number of valid path, ended by the current node
18+
int numPathToCurr = map.ContainsKey(sum-target) ? map[sum-target] : 0;
19+
// update the map with the current sum, so the map is good to be passed to the next recursion
20+
map[sum] = (map.ContainsKey(sum) ? map[sum] : 0) + 1;
21+
// add the 3 parts discussed in 8. together
22+
int res = numPathToCurr + Dfs(curr.left, sum, target, map)
23+
+ Dfs(curr.right, sum, target, map);
24+
// restore the map, as the recursion goes from the bottom to the top
25+
map[sum] -= 1;
26+
return res;
27+
}
28+
}
29+
30+
/**
31+
* Definition for a binary tree node.
32+
* public class TreeNode {
33+
* public int val;
34+
* public TreeNode left;
35+
* public TreeNode right;
36+
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
37+
* this.val = val;
38+
* this.left = left;
39+
* this.right = right;
40+
* }
41+
* }
42+
*/

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ Solutions in various programming languages are provided. Enjoy it.
1414
5. [Add and Search Word Data structure design](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design)
1515
6. [Find All Duplicates in an Array](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array)
1616
7. [Vertical Order Traversal of a Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree)
17+
8. [Path Sum III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/08-Path-Sum-III)
1718

1819
## July LeetCoding Challenge
1920
Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions.

0 commit comments

Comments
 (0)