---
description: '# Easy'
---

# 112. Path Sum

{% hint style="info" %}
Think about edge case and regular case. 自上而下计算更省时间
{% endhint %}

![](https://3288217904-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LxJcc9A1TOyn5a5HJQ4%2F-MANHjFuN98xnjjsHTf5%2F-MANLeZNxZfw2yBbVx5N%2F1592766477380.jpg?alt=media\&token=0839d9b7-f1fd-41d3-9155-75c4dbf29807)

{% tabs %}
{% tab title="Python" %}
```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        # edge case
        if root == None:
            return False
        if root.left == None and root.right == None:
            if root.val == sum:
                return True
            else:
                return False
        
        # regular case
        left = self.hasPathSum(root.left, sum - root.val)
        right = self.hasPathSum(root.right, sum - root.val)
        if left == False and right == False:
            return False
        else:
            return True
```
{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}

Time complexity = $$O(n)$$ , space complexity = $$O(1)$$ . Because the worst case is to traversal all nodes and each node only bring one information `True` or `False`.
