递归,直接把问题转换为叶子节点的val是否等于sum(注:使用return 递归 or 递归的方法将叶子节点的返回值传递至root节点)。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if root is None:
return False
if root.val == sum and root.left is None and root.right is None: return True
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)