> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/tree/112.-path-sum-1.md).

# 112. Path Sum

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MbixhX8hsUYhhJWn4VT%2F-Mbiy3Z0SOU1QrE4ZwcV%2Fimage.png?alt=media\&token=30d6972b-142f-47b8-b4ed-67159e387278)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MbixhX8hsUYhhJWn4VT%2F-Mbiy79RrNs7Zu-qKmrf%2Fimage.png?alt=media\&token=f8231ef9-c1de-4655-9bbc-fb588f31e912)

## keyword: root to leaf

time: O(n)

space: O(n)

```java
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;
        }
        return hasPathSum(root.left, targetSum - root.val) || 
        hasPathSum(root.right, targetSum - root.val);
    }
}
```
