class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
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;
}
// check left and right subtree with reduced sum
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
// Driver code to build tree and test
const root = new TreeNode(5,
new TreeNode(4,
new TreeNode(11,
new TreeNode(7),
new TreeNode(2)
),
null
),
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 tree - no path exists
if (root.left === null && root.right === null) { return root.val === targetSum; }
at leaf, check if path sum matches target
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
recursively check left and right subtrees with updated sum