力扣刷题——111.二叉树的最小深度

111.二叉树的最小深度

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。

示例 1:

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

输出:2

示例 2:

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

输出:5

提示:

树中节点数的范围在 [0, 105] 内

-1000 <= Node.val <= 1000

实现代码(Python):

python 复制代码
from collections import deque
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        queue=deque([root])
        #res=[]
        height=0
        h=1000000

        while queue:
            #level=[]
            size=len(queue)
            height+=1
            for _ in range(size):
                #level.append(queue.popleft())
                node=queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                if not node.left and not node.right:
                    if height<h:
                        h=height
            #res.append(level)
        return h
        

分析

在层序遍历的基础上实现,或者可通过前中后序遍历实现

相关推荐
wutang0ka2 小时前
LeeCode HOT 100 104.二叉树的最大深度
算法
我是鶸2 小时前
secml-malware python library 源码分析及实践
开发语言·python
散峰而望2 小时前
【基础算法】从入门到实战:递归型枚举与回溯剪枝,暴力搜索的初级优化指南
数据结构·c++·后端·算法·机器学习·github·剪枝
setmoon2142 小时前
C++代码规范化工具
开发语言·c++·算法
进击的小头2 小时前
第15篇:MPC的发展方向及展望
python·算法
We་ct2 小时前
LeetCode 35. 搜索插入位置:二分查找的经典应用
前端·算法·leetcode·typescript·个人开发
IT猿手2 小时前
基于 ZOH 离散化与增量 PID 的四旋翼无人机轨迹跟踪控制研究,MATLAB代码
开发语言·算法·matlab·无人机·动态路径规划·openclaw
A923A3 小时前
【洛谷刷题 | 第五天】
算法·字符串·递归·洛谷
SugarFreeOixi3 小时前
MATLAB绘图风格记录NP类型
python·matlab·numpy