DFS递归遍历这棵树,然后去判断到该结点的累计值是否等于target值,然后设置一个标签,去判断是否成功。

class TreeNode:
    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
        self.target = sum
        self.tag=0
        self.DFS(root,0)
        if self.tag==1:
            return True
        else:
            return False

    def isleaf(self,node):
        if node.left == None and node.right == None:
            return True
        else:
            return False

    def DFS(self , root , sum_val):
        # sum_val:root到父节点的累计值
        if root == None:
            return 
        sum_val+=root.val
        if self.isleaf(root):
            if self.target == sum_val:
                self.tag=1
            else:
                return
        else:
            self.DFS(root.left , sum_val)
            self.DFS(root.right , sum_val)

root = TreeNode(5)
root.left=TreeNode(3)
root.right=TreeNode(2)
root.left.left=TreeNode(1)
root.left.right=TreeNode(6)
print(Solution().hasPathSum(root , 9))