-
Notifications
You must be signed in to change notification settings - Fork 0
/
112.path-sum.js
54 lines (51 loc) · 1.14 KB
/
112.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
/*
* @lc app=leetcode id=112 lang=javascript
*
* [112] Path Sum
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} sum
* @return {boolean}
*/
const hasPathSum = function (root, sum) {
if (!root) return false;
if (root.left === null && root.right === null) {
if (root.val === sum) return true;
return false;
}
const stack = [root];
while (stack.length > 0) {
const r = stack.pop();
if (!r.left && !r.right && r.val === sum) {
return true;
}
if (r.right) {
r.right.val += r.val;
stack.push(r.right);
}
if (r.left) {
r.left.val += r.val;
stack.push(r.left);
}
}
return false;
};
// @lc code=end
// recursive
// var hasPathSum = function(root, sum) {
// if (!root) return false;
// if (!root.left && !root.right) { // check leaf
// return sum === root.val;
// } else { // continue DFS
// return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
// }
// };