using System;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public bool HasPathSum(TreeNode root, int targetSum) {
if (root == null) return false; // no node means no path
if (root.left == null && root.right == null) {
return targetSum == root.val; // leaf check if sum matches
}
// check left and right subtrees with reduced sum
return HasPathSum(root.left, targetSum - root.val) || HasPathSum(root.right, targetSum - root.val);
}
public static void Main() {
TreeNode 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)
)
)
);
Solution sol = new Solution();
bool result = sol.HasPathSum(root, 22);
Console.WriteLine(result);
}
}if (root == null) return false; // no node means no path
handle empty subtree as no path
if (root.left == null && root.right == null) {
return targetSum == root.val; // leaf check if sum matches
}
check if current node is leaf and sum matches target
return HasPathSum(root.left, targetSum - root.val) || HasPathSum(root.right, targetSum - root.val);
recurse left and right with reduced sum, return true if any path matches