当前位置:网站首页>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;
}
}
边栏推荐
- 毕业设计:设计秒杀电商系统
- Unity移动端游戏性能优化简谱之 画面表现与GPU压力的权衡
- Smart subway | cloud computing injects wisdom into urban subway transportation
- The maximum expiration time of client secret in azure ad application registration is modified to 2 years
- SQL statement strengthening exercise (MySQL 8.0 as an example)
- PostgreSQL users cannot create table configurations by themselves
- Graduation summary
- idea修改主体颜色
- Spa in SDP
- [Yugong series] go teaching course 002 go language environment installation in July 2022
猜你喜欢
02 specific implementation of LS command
还原窗口位置的微妙之处
Lnk2038 detected a mismatch of "runtimelibrary": the value "md_dynamicrelease" does not match the value "mdd_dynamicdebug" (in main.obj)
透过JVM-SANDBOX源码,了解字节码增强技术原理
02 ls 命令的具体实现
干货!基于GAN的稀有样本生成
分布式系统:what、why、how
laravel admin里百度编辑器自定义路径和文件名
2021 RSC | Drug–target affinity prediction using graph neural network and contact maps
Cesiumjs 2022^ source code interpretation [0] - article directory and source code engineering structure
随机推荐
Balance between picture performance of unity mobile game performance optimization spectrum and GPU pressure
Epidemic strikes -- Thinking about telecommuting | community essay solicitation
【罗技】m720
Is it safe to buy insurance for your children online? Do you want to buy a million dollar medical insurance for your children?
Database SQL statement summary, continuous update
Pytest multi process / multi thread execution test case
[csrf-01] basic principle and attack and defense of Cross Site Request Forgery vulnerability
STM32外接DHT11显示温湿度
支持首次触发的 Go Ticker
02 specific implementation of LS command
[paddleseg source code reading] paddleseg custom data class
Flink学习8:数据的一致性
Tcpclientdemo for TCP protocol interaction
Objective-C string class, array class
深度优先搜索简要讲解(附带基础题)
SQL statement strengthening exercise (MySQL 8.0 as an example)
Msgraphmailbag - search only driveitems of file types
pytest多进程/多线程执行测试用例
Brief explanation of depth first search (with basic questions)
Interpretation of leveldb source code skiplist