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

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

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

#     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
        # 存在 sum = 0,root为空的测试例子
        if not root:
            return False
        sum -= root.val
        # 叶子节点,且sum=0
        if root.left is None and root.right is None and sum == 0:
            return True
        label1 = self.hasPathSum(root.left, sum)
        label2 = self.hasPathSum(root.right, sum)
		# 存在一条线路即可
        return True if label1 or label2 else False
全部评论

相关推荐

深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
评论
6
收藏
分享

创作者周榜

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