-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path437. Path Sum III.js
77 lines (65 loc) · 1.1 KB
/
437. Path Sum III.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/* https://leetcode.com/problems/path-sum-iii/ */
/**
* 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) {
var count = 0;
var compute = function(root, currentSum) {
console.log(root);
if (!root) {
return;
}
currentSum += root.val;
if (currentSum === sum) {
console.log('Matched', root);
count++;
}
if (root.left) {
if (!root.left.started) {
root.left.started = true;
compute(root.left, 0);
}
compute(root.left, currentSum);
}
if (root.right) {
if (!root.right.started) {
root.right.started = true;
compute(root.right, 0);
}
compute(root.right, currentSum);
}
};
compute(root, 0);
return count;
};
var tree = {
val: 1,
left: null,
right: {
val: 2,
left: null,
right: {
val: 3,
left: null,
right: {
val: 4,
left: null,
right: {
val: 5,
left: null,
right: null
}
}
}
}
};
console.log(pathSum(tree, 3));