Skip to content

Commit aecc42f

Browse files
committed
Runtime: 70 ms (Top 80.89%) | Memory: 47.60 MB (Top 75.77%)
1 parent 9e9a355 commit aecc42f

File tree

1 file changed

+11
-27
lines changed

1 file changed

+11
-27
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,11 @@
1-
var pathSum = function(root, targetSum) {
2-
let count = 0;
3-
4-
let hasSum = (node, target) => { //helper function, calculates number of paths having sum equal to target starting from given node
5-
if(node===null){// base case
6-
return;
7-
}
8-
if(node.val===target){// if at any point path sum meets the requirement
9-
count++;
10-
}
11-
//recursive call
12-
hasSum(node.left, target-node.val);
13-
hasSum(node.right, target-node.val);
14-
}
15-
16-
let dfs = (node) => {//dfs on every node and find sum equal to target starting from every node
17-
if(node===null)
18-
return;
19-
dfs(node.left);
20-
dfs(node.right);
21-
hasSum(node,targetSum);// find sum of path starting on this point
22-
}
23-
24-
dfs(root);
25-
26-
return count;
27-
};
1+
// Runtime: 70 ms (Top 80.89%) | Memory: 47.60 MB (Top 75.77%)
2+
3+
var pathSum = function(root, sum, presums = { '0': 1 }, prev = 0) {
4+
if (!root) return 0;
5+
let curr = prev + root.val;
6+
presums[curr] = (presums[curr] || 0) + 1;
7+
let res = (presums[curr - sum] || 0) - !sum;
8+
res += pathSum(root.left, sum, presums, curr) + pathSum(root.right, sum, presums, curr);
9+
presums[curr]--;
10+
return res;
11+
};

0 commit comments

Comments
 (0)