题解 | #二叉树中是否存在节点和为指定值的路径#

二叉树中是否存在节点和为指定值的路径

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

helper 函数:以root根的结点,是否存在到叶子结点使得pathsum为s

# 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 , sum ):
        # write code here
        def helper(root, s):
            if not root:
                return False
            elif not root.left and not root.right and s == root.val:
                return True
            else:
                return helper(root.left, s-root.val) or helper(root.right, s-root.val)
        return helper(root, sum)
全部评论

相关推荐

FFFoly:我也是,现在已经到了学长说的 能面试侃侃而谈的阶段了,但是已经没有公司给我面了
远程面试的尴尬瞬间
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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