题解 | #二叉树中和为某一值的路径(一)#

二叉树中和为某一值的路径(一)

https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c

class Solution:
    def hasPathSum(self , root: TreeNode, sum: int) -> bool:
        def preOder(root, res):
            if not root:     # 如果无子节点且res等于sum,则返回true
                return False # 如果节点为空说明此路径在上一步递归已经被淘汰掉了
            res += root.val 
            if not root.left and not root.right and res == sum:
                return True
            return preOder(root.left, res) or preOder(root.right, res)
        return False if not root else preOder(root, 0)

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-19 14:56
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务