Skip to content

Commit 43171cf

Browse files
authored
Create 437-path-sum-iii.js
1 parent aff75eb commit 43171cf

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

437-path-sum-iii.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @param {number} sum
11+
* @return {number}
12+
*/
13+
function pathSum(root, sum) {
14+
const preSums = new Map([[0, 1]]);
15+
let count = 0;
16+
visit(root, 0);
17+
return count;
18+
19+
function visit(node, preSum) {
20+
if (!node) return;
21+
preSum += node.val;
22+
count += preSums.get(preSum - sum) || 0;
23+
preSums.set(preSum, (preSums.get(preSum) || 0) + 1);
24+
visit(node.left, preSum);
25+
visit(node.right, preSum);
26+
preSums.set(preSum, preSums.get(preSum) - 1);
27+
}
28+
}
29+

0 commit comments

Comments
 (0)