zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【Leetcode刷题Python】111. 二叉树的最小深度

PythonLeetCode二叉树 深度 最小 刷题 111
2023-09-14 09:13:02 时间

1 题目

给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:2

示例 2:

输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

2 解析

递归计算每个子树的最小深度

3 Python实现

class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        if not root.left and not root.right:
            return 1
        min_depth = 10**9
        if root.left:
            min_depth = min(self.minDepth(root.left), min_depth)
        if root.right:
            min_depth = min(self.minDepth(root.right), min_depth)
        return min_depth+1