-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
45 lines (40 loc) · 877 Bytes
/
solution.js
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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} sum
* @return {number}
*/
var pathSum = function(root, sum) {
return helper(root, sum, 0, [])
};
var helper = function(node, sum, curSum, paths) {
if (!node) {
return 0
}
let res = 0
curSum += node.val
paths.push(node.val)
if (curSum === sum) {
res++
}
let tempSum = curSum
for (let i = 0; i < paths.length - 1; i++) {
tempSum -= paths[i]
if (tempSum === sum) {
res++
}
}
if (node.left) {
res += helper(node.left, sum, curSum, paths.slice(0))
}
if (node.right) {
res += helper(node.right, sum, curSum, paths.slice(0))
}
return res
}