Skip to main content

Leetcode - 112. Path Sum

· One min read

https://leetcode.com/problems/path-sum/

Solution 1

/**
* 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 calculatedValue = targetSum - root.val;
if (root.left === null && root.right === null) {
if (calculatedValue === 0) {
return true;
}
return false;
}

return (
hasPathSum(root.left, calculatedValue) ||
hasPathSum(root.right, calculatedValue)
);
};