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.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is 22.
/**
* 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 === null) {
return false;
}
const currentSum = 0;
return checkSum(root, targetSum, currentSum);
};
const checkSum = (root, targetSum, currentSum) => {
if (root === null) {
return false;
}
currentSum = currentSum + root.val;
if (root.left === null && root.right === null) {
return currentSum === targetSum;
}
if (root.left) {
let bool = checkSum(root.left, targetSum, currentSum);
if (bool) {
return bool;
}
}
if (root.right) {
let bool = checkSum(root.right, targetSum, currentSum);
if (bool) {
return bool;
}
}
return false;
};
Top comments (0)