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

【算法题】102. 二叉树的层序遍历

题目

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:

输入:root = [1]
输出:[[1]]
示例 3:

输入:root = []
输出:[]

提示:

树中节点数目在范围 [0, 2000] 内
-1000 <= Node.val <= 1000

题解

class Solution {public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> ret = new ArrayList<List<Integer>>();if (root == null) {return ret;}Queue<TreeNode> queue = new LinkedList<TreeNode>();queue.offer(root);while (!queue.isEmpty()) {List<Integer> level = new ArrayList<Integer>();int currentLevelSize = queue.size();for (int i = 1; i <= currentLevelSize; ++i) {TreeNode node = queue.poll();level.add(node.val);if (node.left != null) {queue.offer(node.left);}if (node.right != null) {queue.offer(node.right);}}ret.add(level);}return ret;}
}

来自力扣官方题解

http://www.lryc.cn/news/298984.html

相关文章:

  • 【龙年大礼】| 2023中国开源年度报告!
  • 本地搭建three.js官方文档
  • 【seata自动化治愈数据库问题解决方案】
  • Node.js之npm单独与批量升级依赖包的方式
  • 66.加一
  • UI自动化之Poco常用断言方式
  • c语言_实现类class的功能 实例
  • [2024]常用的pip指令
  • 【Java EE初阶十二】网络编程TCP/IP协议(二)
  • Idea Git Review插件
  • python的turtle可以定义多个海龟对象
  • LocalAI 部署(主要针对 mac m2 启动)
  • Swift Combine 管道 从入门到精通三
  • 【RISC-V DSP设计】基于CEVA DSP架构的指令集分析(二)-函数列表
  • 蓝桥杯(Web大学组)2022国赛真题:水果消消乐
  • LeetCode--代码详解 155.最小栈
  • 第6讲后端鉴权拦截器实现
  • uniapp从入门到进阶
  • CDN缓存404、403状态码
  • 【Python网络编程之DHCP服务器】
  • 【MySQL】:深入理解并掌握DML和DCL
  • CSP-动态规划-最长公共子序列(LCS)
  • 安装nodejs2011并配置npm仓库
  • 排序C++代码(已更:快速排序,归并排序)
  • CentOS 7.9安装Tesla M4驱动、CUDA和cuDNN
  • Java设计模式——策略
  • 线性代数的本质 1 向量
  • 基于JAVA的贫困地区人口信息管理系统 开源项目
  • 【后端高频面试题--Mybatis篇】
  • 【笔记】Helm-5 Chart模板指南-12 .helmignore文件