forked from JoshCrozier/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0112-path-sum.js
66 lines (54 loc) · 1.49 KB
/
0112-path-sum.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
/**
* 112. Path Sum
* https://leetcode.com/problems/path-sum/
* Difficulty: Easy
*
* Given the root of a binary tree and an integer targetSum, return true if the
* tree has a root-to-leaf path such that adding up all the values along the
* path equals targetSum.
*
* A leaf is a node with no children.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} targetSum
* @return {boolean}
*/
var hasPathSum = function(root, targetSum) {
if (!root) {
return false;
}
const result = [];
traverse(result, root);
return result.includes(targetSum);
};
function traverse(result, node, sum = 0) {
if (!node.left && !node.right) {
result.push(sum + node.val);
}
if (node.left) traverse(result, node.left, sum + node.val);
if (node.right) traverse(result, node.right, sum + node.val);
}
// function hasPathSum(root, targetSum) {
// if (!root) return false;
// let stack = [[root, 0]];
// while (stack.length) {
// let [node, currentSum] = stack.pop();
// if (!node) continue;
// currentSum += node.val;
// if (!node.left && !node.right && currentSum === targetSum) {
// return true;
// }
// stack.push([node.left, currentSum]);
// stack.push([node.right, currentSum]);
// }
// return false;
// }