[LeetCode题解] 111. 二叉树的最小深度

题目链接: https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/.

第一次自己写的代码

class Solution(object):
    min_depth = 2000 #理解为极大值即可
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        self.help(root, 1)
        return self.min_depth

    def help(self, node, depth):
        if not node:
            return
        if not node.left and not node.right:
            self.min_depth = min(self.min_depth, depth)
        self.help(node.left, depth + 1)
        self.help(node.right, depth + 1)

迭代更新版本:

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        if root.left and root.right:
            return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
        elif root.right:
            return 1 + self.minDepth(root.right)
        else:
            return 1 + self.minDepth(root.left)
发布了10 篇原创文章 · 获赞 0 · 访问量 131

猜你喜欢

转载自blog.csdn.net/m0_46134602/article/details/103819531