The key to solving this problem is to remember that root==null isn't a leaf node. Imagine a tree with

1

/

2

\

3

A root==null check will return 3 as true if you thought it was the leaf node. Here the code that does it correctly after ensuring we are considering only the leaf nodes:

```
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
{
return false;
}
if (root.left == null && root.right == null)
{
return root.val - sum == 0;
}
return hasPathSum(root.left, sum - root.val)
|| hasPathSum(root.right, sum - root.val);
}
```