给定一个二叉树,设计一个算法来检查是否存在从根节点到叶子节点的路径,使得其节点值之和等于给定的目标值。

# 示例
# 输入: [5,4,8,11,null,13,4,7,2,null,null,null,1]
# 目标值: 22
# 输出: True

# 定义二叉树节点
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

# 检查从根节点到叶子节点的路径是否存在
# 递归解法
def hasPathSum(root, targetSum):
    if not root:
        return False
    if not root.left and not root.right and root.val == targetSum:
        return True
    targetSum -= root.val
    return hasPathSum(root.left, targetSum) or hasPathSum(root.right, targetSum)

# 创建二叉树
# root = TreeNode(5)
# root.left = TreeNode(4)
# root.right = TreeNode(8)
# root.left.left = TreeNode(11)
# root.left.left.left = TreeNode(7)
# root.left.left.right = TreeNode(2)
# root.right.left = TreeNode(13)
# root.right.right = TreeNode(4)
# root.right.right.right = TreeNode(1)
# result = hasPathSum(root, 22)
# print(result)