当前位置:网站首页>leetcode刷题:二叉树08(N叉树的最大深度)
leetcode刷题:二叉树08(N叉树的最大深度)
2022-07-04 03:51:00 【涛涛英语学不进去】
559.n叉树的最大深度
给定一个 n 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
例如,给定一个 3叉树 :
我们应返回其最大深度,3。
其实一样的,层序遍历即可。
package com.programmercarl.tree;
import java.util.ArrayDeque;
import java.util.Deque;
/** * @ClassName MaxDepth2 * @Descriotion TODO * @Author nitaotao * @Date 2022/7/3 22:24 * @Version 1.0 * 559. N 叉树的最大深度 * https://leetcode.cn/problems/maximum-depth-of-n-ary-tree/ **/
public class MaxDepth2 {
public int maxDepth(Node root) {
int maxDepth = 0;
if (root == null) {
return maxDepth;
}
Deque<Node> deque = new ArrayDeque<Node>();
//层次遍历当前树,一层深度+1
deque.offer(root);
while (!deque.isEmpty()) {
//这句话是核心, size是控制每层有多少元素的变量
int size = deque.size();
maxDepth++;
while (size > 0) {
root = deque.poll();
for (Node item : root.children) {
deque.offer(item);
}
size--;
}
}
return maxDepth;
}
}
边栏推荐
- The three-year revenue is 3.531 billion, and this Jiangxi old watch is going to IPO
- 智慧地铁| 云计算为城市地铁交通注入智慧
- [PaddleSeg 源码阅读] PaddleSeg Transform 的 Normalize操作
- Two commonly used graphics can easily realize data display
- hbuildx中夜神模拟器的配置以及热更新
- [paddleseg source code reading] paddleseg calculation dice
- [Yugong series] go teaching course 002 go language environment installation in July 2022
- Calculate the odd sum of 1~n (1~100 as an example)
- A review of reverse reinforcement learning at Virginia Tech (VT)
- STM32外接DHT11显示温湿度
猜你喜欢
Cesiumjs 2022^ source code interpretation [0] - article directory and source code engineering structure
Select sorting and bubble sorting template
[Logitech] m720
Introduction to asynchronous task capability of function calculation - task trigger de duplication
Msgraphmailbag - search only driveitems of file types
分布式系统:what、why、how
图解网络:什么是热备份路由器协议HSRP?
Objective-C description method and type method
【CSRF-01】跨站请求伪造漏洞基础原理及攻防
微信公众号网页授权
随机推荐
毕业设计:设计秒杀电商系统
Getting started with the go language is simple: go implements the Caesar password
[PaddleSeg 源码阅读] PaddleSeg 自定义数据类
Unity移动端游戏性能优化简谱之 画面表现与GPU压力的权衡
数据库SQL语句汇总,持续更新......
深度优先搜索简要讲解(附带基础题)
ctf-pikachu-CSRF
ctf-pikachu-XSS
Graduation summary
【微服务|openfeign】使用openfeign远程调用文件上传接口
JS实现文字滚动 跑马灯效果
Flink学习8:数据的一致性
“软硬皆施”,助力建成新型云计算数据中心
深入浅出对话系统——使用Transformer进行文本分类
新型数据中心,助力加快构建以数据为关键要素的数字经济
The three-year revenue is 3.531 billion, and this Jiangxi old watch is going to IPO
Katalon框架测试web(二十六)自动发邮件
Two commonly used graphics can easily realize data display
LevelDB源码解读-SkipList
Katalon框架测试web(二十一)获取元素属性断言