Pre-order with a remaining sum
Time O(n) Space O(h)hasPathSum(n, rem): null → false; at a leaf, return rem == n.val; else recurse on both children with rem − n.val.
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
if (root.left == null && root.right == null) return targetSum == root.val;
int rem = targetSum - root.val;
return hasPathSum(root.left, rem) || hasPathSum(root.right, rem);
}
}Verdict: Simple top-down recursion.