当前位置:网站首页>剑指Offer 32.Ⅲ从上到下打印二叉树
剑指Offer 32.Ⅲ从上到下打印二叉树
2022-08-02 03:33:00 【HotRabbit.】
题目
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
提示:
节点总数 <= 1000
思路
广度优先遍历+双端队列
题解
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);
boolean flag = true;
while (!queue.isEmpty()){
int size = queue.size();
Deque<Integer> deque = new LinkedList<>();
for (int i = 0;i < size;i++){
TreeNode node = queue.poll();
if (flag){
deque.offerLast(node.val);
}else {
deque.offerFirst(node.val);
}
if (node.left != null){
queue.add(node.left);
}
if (node.right != null){
queue.add(node.right);
}
}
flag = !flag;
listList.add(new LinkedList<Integer>(deque));
}
return listList;
}
}
边栏推荐
- 调试九法准则
- HAL库笔记——通过按键来控制LED(基于正点原子STM32F103ZET6精英板)
- TC358860XBG BGA65 东芝桥接芯片 HDMI转MIPI
- CCF刷题之旅--第一题
- Comparative analysis of mobile cloud IoT pre-research and Alibaba Cloud development
- 引擎开发日志:重构骨骼动画系统
- 【Popular Science Post】UART Interface Communication Protocol
- 【TCS3200 color sensor and Arduino realize color recognition】
- STM32 CAN 介绍以及相关配置
- Comparison between Boda Industrial Cloud and Alibaba Cloud
猜你喜欢
随机推荐
Lightly 支持 Markdown 文件在线编写(文中提供详细 Markdown 语法)
进程(中):进程状态、进程地址空间
简单的RC滤波电路
GM8775C规格书,MIPI转LVDS,MIPI转双路LVDS分享
【Connect the heart rate sensor to Arduino to read the heart rate data】
GM8284DD,GM8285C,GM8913,GM8914,GM8905C,GM8906C,国腾振芯LVDS类芯片
AD PCB导出Gerber文件(非常详细的步骤)
汇编语言跳转指令总结
MC1496乘法器
为什么D类音频功放可以免输出滤波器
CCF刷题之旅--第一题
龙讯LT6911系列C/UXC/UXB/GXC/GXB芯片功能区别阐述
将ORCAD原理图导入allegro中进行PCB设计
GM8775C MIPI转LVDS调试心得分享
全加器高进位和低进位的理解
【plang 1.4.6】Plang高级编程语言(发布)
哈希表解题方法
引擎开发日志:重构骨骼动画系统
Type c PD 电路设计
增量编译技术在Lightly中的实践









