当前位置:网站首页>leetcode刷题:二叉树09(二叉树的最小深度)
leetcode刷题:二叉树09(二叉树的最小深度)
2022-07-04 03:51:00 【涛涛英语学不进去】
111.二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],

返回它的最小深度 2.
依旧使用层序遍历,当这层不满,且!!!出现了叶子节点,则出现最小深度。
package com.programmercarl.tree;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
/** * @ClassName MinDepth * @Descriotion TODO * @Author nitaotao * @Date 2022/7/3 22:32 * @Version 1.0 * 111. 二叉树的最小深度 * https://leetcode.cn/problems/minimum-depth-of-binary-tree/ **/
public class MinDepth {
public int minDepth(TreeNode root) {
//层序遍历,哪一行不满,即有缺省,则为最短深度
int minDepth = 0;
if (root == null) {
return minDepth;
}
Deque<TreeNode> deque = new ArrayDeque<TreeNode>();
deque.offer(root);
int length = 1;
while (!deque.isEmpty()) {
int size = deque.size();
boolean flag = false;
while (size > 0) {
root = deque.poll();
//出现叶子结点
if (root.left == null && root.right == null) {
flag = true;
}
if (root.left != null) {
deque.offer(root.left);
}
if (root.right != null) {
deque.offer(root.right);
}
size--;
}
length *= 2;
minDepth++;
if (deque.size() != length && flag) {
return minDepth;
}
}
return minDepth;
}
}

边栏推荐
- pytest多进程/多线程执行测试用例
- [PaddleSeg 源码阅读] PaddleSeg Transform 的 Normalize操作
- 支持首次触发的 Go Ticker
- 如何有效远程办公之我见 | 社区征文
- Pointer array and array pointer
- Two sides of the evening: tell me about the bloom filter and cuckoo filter? Application scenario? I'm confused..
- Katalon framework tests web (XXI) to obtain element attribute assertions
- '2'&gt;' 10'==true? How does JS perform implicit type conversion?
- 【华为云IoT】读书笔记之《万物互联:物联网核心技术与安全》第3章(上)
- Katalon框架测试web(二十一)获取元素属性断言
猜你喜欢

02 specific implementation of LS command

Balance between picture performance of unity mobile game performance optimization spectrum and GPU pressure

functools下的reduce函数

idea修改主体颜色

laravel admin里百度编辑器自定义路径和文件名
![CesiumJS 2022^ 源码解读[0] - 文章目录与源码工程结构](/img/ba/c1d40de154344ccc9f2fd1dd4cb12f.png)
CesiumJS 2022^ 源码解读[0] - 文章目录与源码工程结构

分布式系统:what、why、how

Wechat official account web page authorization

量子力学习题

Flink学习8:数据的一致性
随机推荐
干货!基于GAN的稀有样本生成
Idea modify body color
函数计算异步任务能力介绍 - 任务触发去重
CesiumJS 2022^ 源码解读[0] - 文章目录与源码工程结构
Select sorting and bubble sorting template
Spa in SDP
[Huawei cloud IOT] reading notes, "Internet of things: core technology and security of the Internet of things", Chapter 3 (I)
10 reasons for not choosing to use free virtual hosts
02 ls 命令的具体实现
如何远程办公更有效率 | 社区征文
SDP中的SPA
Support the first triggered go ticker
Is it safe to buy insurance for your children online? Do you want to buy a million dollar medical insurance for your children?
Mindmanager2022 efficient and easy to use office mind map MindManager
SQL語句加强練習(MySQL8.0為例)
vue多级路由嵌套怎么动态缓存组件
How was my life in 2021
深入浅出对话系统——使用Transformer进行文本分类
[webrtc] M98 Ninja build and compile instructions
2022-07-03:数组里有0和1,一定要翻转一个区间,翻转:0变1,1变0。 请问翻转后可以使得1的个数最多是多少? 来自小红书。3.13笔试。