class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function hasPathSum(root, targetSum) {
if (root === null) return false; // no node means no path
// if leaf node, check if value equals targetSum
if (root.left === null && root.right === null) {
return root.val === targetSum;
}
// recursively check left and right subtrees with reduced sum
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
// driver code
const root = new TreeNode(5,
new TreeNode(4,
new TreeNode(11,
new TreeNode(7),
new TreeNode(2)
)
),
new TreeNode(8,
new TreeNode(13),
new TreeNode(4,
null,
new TreeNode(1)
)
)
);
console.log(hasPathSum(root, 22));if (root === null) return false;
handle empty node as no path
if (root.left === null && root.right === null) { return root.val === targetSum; }
check if leaf node value matches remaining sum
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
recurse left and right with updated sum, return true if any path matches