python递归

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

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

递归先序遍历
判断当前节点是否为空,递归退出条件
判断条件:叶子节点+和等于sum,返回真,否则返回左子树和右子树的或结果;

# 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 ):
        def pre_order(root,res):
            if not root:return False

            res+=root.val
            if not root.left and not root.right and res==sum:
                return True
            return pre_order(root.left, res) or pre_order(root.right, res)
        return False if not root else pre_order(root,0)
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务