-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
52 lines (46 loc) · 1.45 KB
/
Solution.cs
File metadata and controls
52 lines (46 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class Solution
{
public int PathSum(TreeNode root, int targetSum)
{
if (root is null) return 0;
int ans = 0;
Queue<TreeNode> queue = new();
queue.Enqueue(root);
while (queue.Count > 0)
{
var currRoot = queue.Dequeue();
if (currRoot.left is not null) queue.Enqueue(currRoot.left);
if (currRoot.right is not null) queue.Enqueue(currRoot.right);
ans += DFS(currRoot, targetSum, 0);
}
return ans;
}
private int DFS(TreeNode node, int targetSum, long currentSum)
{
if (node is null) return 0;
if (currentSum > targetSum) return 0;
currentSum += node.val;
int count = (targetSum == currentSum) ? 1 : 0;
return count
+ DFS(node.left, targetSum, currentSum)
+ DFS(node.right, targetSum, currentSum);
}
public int PathSum2(TreeNode root, int targetSum)
{
var count = 0;
var cache = new Dictionary<long, int>();
cache[0] = 1;
void dfs(TreeNode node, long sum)
{
if (node is null) return;
sum += node.val;
cache[sum] = cache.GetValueOrDefault(sum, 0) + 1;
if (cache.TryGetValue(sum - targetSum, out int c)) count += c;
dfs(node.left, sum);
dfs(node.right, sum);
cache[sum]--; // backtrack
}
dfs(root, 0);
return count;
}
}