您当前的位置: 首页 >  Python

Better Bench

暂无认证

  • 1浏览

    0关注

    695博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

Better Bench 发布时间:2022-08-10 22:42:00 ,浏览量:1

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
关注
打赏
1665674626
查看更多评论
立即登录/注册

微信扫码登录

0.0389s