← 返回题库
初级

路径总和

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def solve():
    def hasPathSum(root, targetSum):
        if not root:
            return False
        if not root.left and not root.right:
            return targetSum == root.val
        return hasPathSum(root.left, targetSum - root.val) or hasPathSum(root.right, targetSum - root.val)
    root = TreeNode(5, TreeNode(4, TreeNode(11, TreeNode(7), TreeNode(2))), TreeNode(8, TreeNode(13), TreeNode(4, None, TreeNode(1))))
    print(hasPathSum(root, 22))

示例

输入
solve()
期望输出
True
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码