-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPathSum.js
More file actions
44 lines (32 loc) · 996 Bytes
/
Copy pathPathSum.js
File metadata and controls
44 lines (32 loc) · 996 Bytes
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
/**
* 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 checkSum = function(curr, accumulator, targetSum) {
if (curr === null) {
return false;
}
accumulator += curr.val;
if (accumulator == targetSum && curr.left === null && curr.right === null) {
return true;
}
return checkSum(curr.left, accumulator, targetSum) || checkSum(curr.right, accumulator, targetSum);
}
var hasPathSum = function(root, targetSum) {
if (root === null) {
return false;
}
if (root.val == targetSum && root.left === null && root.right === null){
return true;
}
return checkSum(root.left, root.val, targetSum) || checkSum(root.right, root.val, targetSum);
};