当前位置:网站首页>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;
}
}
边栏推荐
- 干货!基于GAN的稀有样本生成
- Detailed explanation of PPTC self recovery fuse
- 疫情来袭--远程办公之思考|社区征文
- MySQL maxscale realizes read-write separation
- Sales management system of lightweight enterprises based on PHP
- SQL語句加强練習(MySQL8.0為例)
- Flink学习7:应用程序结构
- postgresql 用户不能自己创建表格配置
- 如何有效远程办公之我见 | 社区征文
- Two commonly used graphics can easily realize data display
猜你喜欢
Idea modify body color
Two sides of the evening: tell me about the bloom filter and cuckoo filter? Application scenario? I'm confused..
Idea configuration 360zip open by default -- external tools
[Logitech] m720
PostgreSQL users cannot create table configurations by themselves
Wechat official account web page authorization
Confession code collection, who says program apes don't understand romance
Katalon框架测试web(二十六)自动发邮件
Getting started with the go language is simple: go implements the Caesar password
Lnk2038 detected a mismatch of "runtimelibrary": the value "md_dynamicrelease" does not match the value "mdd_dynamicdebug" (in main.obj)
随机推荐
Unity移动端游戏性能优化简谱之 画面表现与GPU压力的权衡
Penetration practice - sqlserver empowerment
LevelDB源码解读-SkipList
程序员远程办公喜忧参半| 社区征文
Pointer array and array pointer
Objective-C description method and type method
如何有效远程办公之我见 | 社区征文
Two sides of the evening: tell me about the bloom filter and cuckoo filter? Application scenario? I'm confused..
Activiti7 task service - process variables (setvariable and setvariablelocal)
Sales management system of lightweight enterprises based on PHP
Spa in SDP
PostgreSQL users cannot create table configurations by themselves
Wechat official account web page authorization
CesiumJS 2022^ 源码解读[0] - 文章目录与源码工程结构
pytest多进程/多线程执行测试用例
SQL語句加强練習(MySQL8.0為例)
【webrtc】m98 ninja 构建和编译指令
SDP中的SPA
Why is the probability of pod increasing after IPtable
[PaddleSeg 源码阅读] PaddleSeg 自定义数据类