437._path_sum_iii.md 873 字节
Newer Older
K
KEQI HUANG 已提交
1
### 437. Path Sum III
K
KEQI HUANG 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16



题目:
<https://leetcode.com/problems/path-sum-iii/>


难度:
Easy

思路:




K
KEQI HUANG 已提交
17
```python
K
KEQI HUANG 已提交
18 19 20 21 22 23 24
class Solution(object):
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
K
KEQI HUANG 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
        if not root:
            return 0
        res = self.auxPathSum(root, sum)
        res += self.pathSum(root.left, sum)
        res += self.pathSum(root.right, sum)
        return res
    def auxPathSum(self, root, sum):
        if not root:
            return 0
        if sum == root.val:
            # 因为可能有负值, 所以sum为0也会有解, 必须加上
            return 1 + self.auxPathSum(root.left, 0) + self.auxPathSum(root.right, 0) 
        else:
            return self.auxPathSum(root.left, sum - root.val) + self.auxPathSum(root.right, sum - root.val)
```