# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param root TreeNode类
# @param sum int整型
# @return bool布尔型
#
# 深度优先遍历,递归的形式求解
class Solution:
def hasPathSum(self , root: TreeNode, sum: int) -> bool:
# write code here
# 存在 sum = 0,root为空的测试例子
if not root:
return False
sum -= root.val
# 叶子节点,且sum=0
if root.left is None and root.right is None and sum == 0:
return True
label1 = self.hasPathSum(root.left, sum)
label2 = self.hasPathSum(root.right, sum)
# 存在一条线路即可
return True if label1 or label2 else False