```
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) // base case.
return false;
if (root.val == sum && root.left == null && root.right == null) // The node should be the leaf node at which the sum is equal to its value.
return true;
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); // keep reducing the sum during recursion until it is equal to the value of leaf node.
}
```