首页 > 其他 > 详细

leetcood学习笔记-111-二叉树的最小深度

时间:2019-03-27 13:23:53      阅读:131      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

第一次提交:

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        if root.left and root.right:
            return min(self.minDepth(root.left)+1,self.minDepth(root.right)+1)
        if not root.left and root.right:
            return self.minDepth(root.right)+1
        if not root.right and root.left:
            return self.minDepth(root.left)+1
        if not root.left and not root.right:
            return 1

优化后:

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0
        if not root.left or not root.right:
            return 1 + max(self.minDepth(root.right), self.minDepth(root.left))
        else:
            return 1 + min(self.minDepth(root.right), self.minDepth(root.left))

 

leetcood学习笔记-111-二叉树的最小深度

原文:https://www.cnblogs.com/oldby/p/10606640.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!