当前位置:网站首页>刷题记录----二叉树的层序遍历
刷题记录----二叉树的层序遍历
2022-07-28 05:26:00 【HandsomeDog_L】
目录
结合辅助队列,两层循环,从上到下,从左到右遍历,结果即为层序遍历
题目描述:给定一个二叉树,返回其层序遍历的结果

结合辅助队列,两层循环,从上到下,从左到右遍历,结果即为层序遍历
void levelTraverse(TreeNode root) {
if (root == null) return;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
// 从上到下遍历二叉树的每一层
while (!q.isEmpty()) {
int sz = q.size();
// 从左到右遍历每一层的每个节点
for (int i = 0; i < sz; i++) {
TreeNode cur = q.poll();
// 将下一层节点放入队列
if (cur.left != null) {
q.offer(cur.left);
}
if (cur.right != null) {
q.offer(cur.right);
}
}
}
}递归:
class Solution {
List<List<Integer>> list = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
dns(root,0);
return list;
}
public void dns(TreeNode node,int lever){
if(node == null) return;
if(list.size()==lever) list.add(new ArrayList<Integer>());
list.get(lever).add(node.val);
dns(node.left,lever+1);
dns(node.right,lever+1);
}
}边栏推荐
- Relative path and absolute path
- Filter
- QT custom sliding button (beautiful and easy to use)
- Common table expression CTE in Clickhouse
- MFC 使用控制台打印程序信息
- qt解析字符串转为json数据并解析
- Talk about the "hybrid mode" of esxi virtual switch and port group
- Design and analysis of contactor coil control circuit
- 微信小程序自定义编译模式
- Find the network address and broadcast address of the host according to the IP address and subnet mask
猜你喜欢

Antenna effect solution

Matlab simulation of radar imaging 1 - LFM signal and its spectrum

2022-06-07 responsebodyadvice caused the spring frame problem in swagger

MATLAB signal processing

Redhawk Dynamic Analysis

七夕送女朋友什么礼物好?不会送礼的男生速看!

Machine learning note 5 - logistic regression

2022-06-07 ResponseBodyAdvice导致Swagger出现弹框问题

qt设置加载界面的几种方法

Icc2 (III) clock tree synthesis
随机推荐
Use and safe shutdown of qthread thread in QT
What's a good gift for your girlfriend on Chinese Valentine's day? Boys who can't give gifts, look!
OpenGL development environment configuration [vs2017] + frequently asked questions
Pytorch learning notes
多个ics日历合并成单个ics日历
当前学习进度
Icc2 (III) clock tree synthesis
qt解决每次修改完ui文件都要重新构建的问题
Get the current directory in QT
suger BI 创建任务
微信小程序自定义编译模式
Measure computer battery capacity
Problems of font modification and line spacing in word automatic directory
How to test industrial Ethernet cables (using fluke dsx-8000)?
小程序:生命周期
Filter
QT batch operation control and set signal slot
Perl introductory learning (XI) file operation
qt实现将相关信息输出到日志文件
【学习笔记】工具