当前位置:网站首页>#yyds干货盘点# 解决剑指offer:把二叉树打印成多行
#yyds干货盘点# 解决剑指offer:把二叉树打印成多行
2022-06-22 21:35:00 【51CTO】
1.简述:
描述
给定一个节点数为 n 二叉树,要求从上到下按层打印二叉树的 val 值,同一层结点从左至右输出,每一层输出一行,将输出的结果存放到一个二维数组中返回。例如:
给定的二叉树是{1,2,3,#,#,4,5}

该二叉树多行打印层序遍历的结果是[[1],[2,3],[4,5]]
数据范围:二叉树的节点数 ,
要求:空间复杂度
,时间复杂度
输入描述:
给定一个二叉树的根节点
示例1
输入:
返回值:
示例2
输入:
返回值:
示例3
输入:
返回值:
示例4
输入:
返回值:
2.代码实现:
import java.util.*;
public class Solution {
//层次遍历
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
TreeNode head = pRoot;
ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer> >();
if(head == null)
//如果是空,则直接返回空数组
return res;
//队列存储,进行层次遍历
Queue<TreeNode> temp = new LinkedList<TreeNode>();
temp.offer(head);
TreeNode p;
while(!temp.isEmpty()){
//记录二叉树的某一行
ArrayList<Integer> row = new ArrayList<Integer>();
int n = temp.size();
//因先进入的是根节点,故每层节点多少,队列大小就是多少
for(int i = 0; i < n; i++){
p = temp.poll();
row.add(p.val);
//若是左右孩子存在,则存入左右孩子作为下一个层次
if(p.left != null)
temp.offer(p.left);
if(p.right != null)
temp.offer(p.right);
}
res.add(row);
}
return res;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
边栏推荐
- 如何使用enum数据类型
- Tp5.1 solving cross domain problems
- After passing the hcip exam, I still failed to change my career. What do professional network workers value most
- c# sqlsugar,hisql,freesql orm框架全方位性能测试对比 sqlserver 性能测试
- 在Word中自定义多级列表样式
- Longest word in output string
- 昆仑分布式数据库Sequence功能及其实现机制
- Redis cache
- Tp5.1 upload excel file and read its contents
- 为什么大家很少使用外键了?
猜你喜欢

KunlunDB查询优化(三)排序下推

Programmers' choice of taking private jobs and part-time jobs

Synchronization circuit and cross clock domain circuit design 2 -- cross clock domain transmission (FIFO) of multi bit signals

Learning the interpretable representation of quantum entanglement, the depth generation model can be directly applied to other physical systems

Tp5.1 upload excel file and read its contents

Leakcanary source code (2)

2022天梯赛-全国总决赛复盘赛

【ARM】讯为rk3568开发板lvds屏设置横屏显示

Digital data was invited to participate in Nantong enterprise digital transformation Seminar

【GO】Go数组和切片(动态数组)
随机推荐
What does password security mean? What are the password security standard clauses in the ISO 2.0 policy?
OJ每日一练—— 班级就餐
[arm] it is reported that horizontal display is set for LVDS screen of rk3568 development board
2. interface (calculator)
07 项目成本管理
wallys/WiFi6 MiniPCIe Module 2T2R 2 × 2.4GHz 2x5GHz
OJ每日一练——跨越2020
RedisTemplate使用遇到\x00的问题
tp5.1上传excel文件并读取其内容
[go] go polymorphism
【STM32技巧】使用STM32 HAL库的硬件I2C驱动RX8025T实时时钟芯片
[STM32 skill] use the hardware I2C of STM32 Hal library to drive rx8025t real-time clock chip
KunlunDB备份和恢复
瑞达期货安全么?期货开户都是哪些流程?期货手续费怎么降低?
What do you pay special attention to when you insert / update / delete / obtain millions of rows of data in a DML statement?
web缓存技术
JSBridge
为什么大家很少使用外键了?
tp5.1解决跨域
OJ daily practice - class dining