当前位置:网站首页>剑指Offer 32.Ⅱ从上到下打印二叉树
剑指Offer 32.Ⅱ从上到下打印二叉树
2022-08-02 03:33:00 【HotRabbit.】
题目
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
思路
相较于Ⅰ(剑指Offer 32.从上到下打印二叉树_HotRabbit.的博客-CSDN博客)多个在队列大小内循环即可
题解
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> listList = new ArrayList<List<Integer>>();
if (root == null){
return listList;}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()){
int size = queue.size();
List<Integer> list = new ArrayList<>();
for (int i = 0;i < size;i++){
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null){
queue.add(node.left);
}
if (node.right != null){
queue.add(node.right);
}
}
listList.add(list);
}
return listList;
}
}
边栏推荐
猜你喜欢
随机推荐
【Popular Science Post】UART Interface Communication Protocol
为什么D类音频功放可以免输出滤波器
电脑基本知识
Chrome 里的小恐龙游戏是怎么做出来的?
vector的使用和模拟实现:
Lightly:新一代的C语言IDE
Case | industrial iot solutions, steel mills high-performance security for wisdom
Comparative analysis of OneNET Studio and IoT Studio
AD8361检波器
STM32F4 CAN 配置注意的细节问题
Host your own website with Vercel
实现动态库(DLL)之间内存统一管理
【详解】线程池及其自定义线程池的实现
Application of electronic flow on business trip
IDEA2021.2安装与配置(持续更新)
最第k大的数的一般性问题
Type c PD 电路设计
汇编语言跳转指令总结
UKlog.dat和QQ,微信文件的转移
剑指Offer 35.复杂链表的复制









