We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent aff75eb commit 43171cfCopy full SHA for 43171cf
437-path-sum-iii.js
@@ -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