-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
/
Copy pathSolution.ts
31 lines (30 loc) · 940 Bytes
/
Solution.ts
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
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function pathSum(root: TreeNode | null, targetSum: number): number {
const cnt: Map<number, number> = new Map();
const dfs = (node: TreeNode | null, s: number): number => {
if (!node) {
return 0;
}
s += node.val;
let ans = cnt.get(s - targetSum) ?? 0;
cnt.set(s, (cnt.get(s) ?? 0) + 1);
ans += dfs(node.left, s);
ans += dfs(node.right, s);
cnt.set(s, (cnt.get(s) ?? 0) - 1);
return ans;
};
cnt.set(0, 1);
return dfs(root, 0);
}