-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathSum.js
More file actions
32 lines (27 loc) · 892 Bytes
/
pathSum.js
File metadata and controls
32 lines (27 loc) · 892 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
/**
* LeetCode 112. Path Sum
* https://leetcode.com/problems/path-sum/description/
*
* 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.
*/
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|null} root
* @param {number} targetSum
* @return {boolean}
*/
function hasPathSum(root, targetSum) {
if (!root) return false;
if (!root.left && !root.right) {
return targetSum === root.val;
}
const newTarget = targetSum - root.val;
return hasPathSum(root.left, newTarget) || hasPathSum(root.right, newTarget);
}
module.exports = { hasPathSum, TreeNode };