1. # Definition for a binary tree node.
    2. # class TreeNode:
    3. # def __init__(self, x):
    4. # self.val = x
    5. # self.left = None
    6. # self.right = None
    7. class Solution:
    8. def hasPathSum(self, root: TreeNode, sum: int) -> bool:
    9. # 自顶向下
    10. def dfs(root, cusum):
    11. if root is None:
    12. return False
    13. if root.left is None and root.right is None:
    14. return cusum + root.val == sum
    15. return dfs(root.left, cusum+root.val) or dfs(root.right, cusum+root.val)
    16. return dfs(root, cusum=0) if root else False