当前位置:网站首页>剑指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;
}
}
边栏推荐
猜你喜欢
随机推荐
Basic IO (below): soft and hard links and dynamic and static libraries
【多线程】线程安全保护机制
AD实战篇
path 修补文件命令
GM8775C MIPI转LVDS调试资料分享
电脑基本知识
408-Binary tree-preorder inorder postorder level traversal
机械臂运动学解析
DMA相应外设映射
增量编译技术在Lightly中的实践
向龙芯2K1000板子上烧写中标麒麟系统
【TCS3200 color sensor and Arduino realize color recognition】
TeamCode 产品 UI 全新升级,快来体验吧
【Popular Science Post】UART Interface Communication Protocol
为什么D类音频功放可以免输出滤波器
[Arduino connected to GP2Y1014AU0F dust sensor]
proteus数字电路仿真——入门实例
Comparative analysis of OneNET Studio and IoT Studio
Mac安装MySQL详细教程
2020 - AAAI - 图像修复 Image Inpainting论文导读 -《Region Normalization for Image Inpainting》