forked from drjkuo/leetcode-javascript-python3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path112.PathSum.js
More file actions
43 lines (40 loc) · 1.2 KB
/
112.PathSum.js
File metadata and controls
43 lines (40 loc) · 1.2 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
40
41
42
43
/**
* 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}
*/
var hasPathSum = function(root, sum) {
if (root === null) return false;
// if (root === null && sum === 0) return true;
return helper(root, sum);
};
let helper = function(node, remaining) // make sure of end condition
{
if (node === null) return false; // if current node is null then terminate
if (node.val === remaining && node.left === null && node.right === null) return true; // true condition: node.val && leaf
return helper(node.left, remaining - node.val) || helper(node.right, remaining - node.val);
}
/**
* 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}
*/
var hasPathSum = function(root, sum) {
if (root === null) return false;
if (root.val === sum && root.left === null && root.right === null) return true;
return (hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val));
};