当前位置:网站首页>剑指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
Related Topics
- 树
- 广度优先搜索
- 二叉树
思路
BFS广度优先遍历
题解
class Solution {
public int[] levelOrder(TreeNode root) {
if (root == null){
return new int[0];
}
Queue<TreeNode> queue = new LinkedList<>();
List<Integer> list = new ArrayList<>();
queue.add(root);
while (!queue.isEmpty()){
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null){
queue.add(node.left);
}
if (node.right != null){
queue.add(node.right);
}
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
}
边栏推荐
猜你喜欢
随机推荐
HDMI转MIPI CSI东芝转换芯片-TC358743XBG/TC358749XBG
【LeetCode】求和
使用buildroot制作根文件系统(龙芯1B使用)
【详解】优先级队列的底层实现
引擎开发日志:OpenGL资源多线程加载
uniCloud address book combat
openwrt RK3568_EVB移植
【TCS3200 color sensor and Arduino realize color recognition】
GM8775C MIPI转LVDS调试心得分享
GM8775C规格书,MIPI转LVDS,MIPI转双路LVDS分享
R语言 —— 多元线性回归
Laptop charging problems
list:list的介绍和模拟实现
install 命令
Pylon CLI 低成本的本地环境管控工具应用实例
Comparative analysis of OneNET Studio and IoT Studio
增量编译技术在Lightly中的实践
Cadence allegro导出Gerber文件(制板文件)图文操作
Case | industrial iot solutions, steel mills high-performance security for wisdom
Altium Designer基础知识