当前位置: 首页 > java >正文

【Java】【力扣】102.二叉树层序遍历

思路

一个辅助队列(初始化队列:根节点入队)

一个节点 出队,他的左右孩子入队

循环 直到队列为空

举例

代码

 public List<List<Integer>> levelOrder(TreeNode root) {if (root==null){return new ArrayList<List<Integer>>();}Queue<TreeNode> queue = new LinkedList<>();//结果数据List<List<Integer>> resultList=new ArrayList<>();//初始化 入队queue.offer(root);//层循环while (!queue.isEmpty()) {//创建level层listList<Integer> level=new ArrayList<>();int curSize=queue.size();//队列当层循环for (int i = 0; i < curSize; i++) {//出队,并得到节点TreeNode node =queue.poll();//如果左孩子不为空,入队if (node.left!= null) {queue.offer(node.left);}//如果右孩子不为空,入队if (node.right != null) {queue.offer(node.right);}//level.add(得到的节点)level.add(node.val);}//result,添加层节点resultList.add(level);}return resultList;}

总结

1. ”if else“和 ” if if“对比

图todo

2.循环变量 .length/.size ,要注意”是否会被改变“

3.习惯性 判空(方法开头)

1-对于传进来的参数,如果为空

其他 todo待补充

http://www.xdnf.cn/news/15061.html

相关文章:

  • 【TCP/IP】18. 因特网服务质量
  • PyTorch 与 Spring AI 集成实战
  • 【操作系统】线程
  • vue3 el-input 通过数组 获取显示
  • docker 启动中间件
  • LeetCode 148 排序链表解析:高效归并排序实现
  • 搭建渗透测试环境
  • React之旅-05 List Key
  • 力扣 hot100 Day40
  • Java 大视界 -- Java 大数据在智能交通智能停车诱导与车位共享中的应用(341)
  • AI翻唱——So-VITS-SVC
  • mvn能只test单独一个文件吗
  • 攻防世界——web题catcat-new session值伪造
  • 电脑息屏工具,一键黑屏超方便
  • 【LeetCode100】--- 1.两数之和【复习回滚】
  • 学习日记-spring-day45-7.10
  • 深入理解 Linux 中的 stat 函数与文件属性操作
  • 710 Mybatis实战
  • Using Spring for Apache Pulsar:Transactions
  • PyTorch Tensor 操作入门:转换、运算、维度变换
  • 【TCP/IP】11. IP 组播
  • 深入解析JVM内存结构与垃圾回收机制
  • Boost.Asio学习(3):异步读写
  • Spring for Apache Pulsar->Reactive Support->Message Production
  • Linux的DNS域名解析服务
  • 多线程 JAVA
  • 表达式索引海外云持久化实践:关键技术解析与性能优化
  • 深入浅出 Python Asynchronous I/O:从 asyncio 入门到实战
  • 2025.07.09华为机考真题解析-第二题200分
  • FlashAttention 快速安装指南(避免长时间编译)