-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0112-path-sum.js
More file actions
39 lines (33 loc) · 1.02 KB
/
0112-path-sum.js
File metadata and controls
39 lines (33 loc) · 1.02 KB
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
/**
* Path Sum
* Time Complexity: O(N)
* Space Complexity: O(H)
*/
var hasPathSum = function (root, targetSum) {
if (!root) {
return false;
}
let pathStack = [];
pathStack.push([root, root.val]);
while (pathStack.length > 0) {
let currentPathData = pathStack.pop();
let currentTreeNode = currentPathData[0];
let accumulatedSum = currentPathData[1];
if (!currentTreeNode.left && !currentTreeNode.right) {
if (accumulatedSum === targetSum) {
return true;
}
}
let rightChildNode = currentTreeNode.right;
if (rightChildNode) {
let newSumForRight = accumulatedSum + rightChildNode.val;
pathStack.push([rightChildNode, newSumForRight]);
}
let leftChildNode = currentTreeNode.left;
if (leftChildNode) {
let newSumForLeft = accumulatedSum + leftChildNode.val;
pathStack.push([leftChildNode, newSumForLeft]);
}
}
return false;
};