日野弥生:勉強しよう

LeetCode 111 - 二叉树的最小深度

发表于2025年03月06日

#树 #二叉树 #广度优先搜索 #深度优先搜索

递归解题,整体思路都是先根遍历,在根节点把深度传递到子树中,当遇到叶子节点时,更新最小深度。

本题要注意,最小值的初始值可以考虑设python3的整型最大值,但是如果函数没有修改该值,应该置0。

class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        minDepth = sys.maxsize
        def minDepthIMPL(root: Optional[TreeNode], depth: int):
            nonlocal minDepth
            if not root:
                return
            if not root.left and not root.right:
                minDepth = minDepth if minDepth < depth else depth
                return
            minDepthIMPL(root.left, depth + 1)
            minDepthIMPL(root.right, depth + 1)
        minDepthIMPL(root, 1)
        # 业务函数没有修改该值,则返回0
        return minDepth if minDepth < sys.maxsize else 0

フラッシュタブ:LeetCode

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

上一篇

LeetCode 563 - 二叉树的坡度

下一篇

LeetCode 100 - 相同的树