当前位置:网站首页>【leetcode】102.二叉树的层序遍历
【leetcode】102.二叉树的层序遍历
2022-04-23 10:27:00 【前端corner】
题目
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
树中节点数目在范围 [0, 2000] 内
-1000 <= Node.val <= 1000
思路

- 二叉树的层序遍历即一层一层从左往右遍历,利用队列这种数据结构先进先出的特点即可以完成。
代码

/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
/** * @param {TreeNode} root * @return {number[][]} */
var levelOrder = function(root) {
if(!root) return []
let queue = [root]
let res = []
while(queue.length){
const len = queue.length
let curLevel = [] //存放每一层的节点
for(let i = 0 ; i < len ; i++){
const curNode = queue.shift()
curLevel.push(curNode.val)
if(curNode.left) queue.push(curNode.left)
if(curNode.right) queue.push(curNode.right)
}
res.push(curLevel) //存放当层遍历结果
}
return res
};
复杂度
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)
关注我的专栏,每天更新三道leetcode题解,一起变强!
版权声明
本文为[前端corner]所创,转载请带上原文链接,感谢
https://blog.csdn.net/laplacepoisson/article/details/124359003
边栏推荐
- 通过流式数据集成实现数据价值(4)-流数据管道
- Common SQL statements of DBA (6) - daily management
- Sim Api User Guide(5)
- 707. Design linked list (linked list)
- Realizing data value through streaming data integration (5) - stream processing
- What are the system events of Jerry's [chapter]
- Net start MySQL MySQL service is starting MySQL service failed to start. The service did not report any errors.
- 59、螺旋矩阵(数组)
- Operation of 2022 tea artist (primary) test question simulation test platform
- LeetCode-608. 树节点
猜你喜欢

Windows installs redis and sets the redis service to start automatically
![[untitled]](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
[untitled]

Arm debugging (1): two methods to redirect printf to serial port in keil

Solve the problem of installing VMware after uninstalling

Juc并发编程07——公平锁真的公平吗(源码剖析)

/Can etc / shadow be cracked?

【无标题】

一文看懂 LSTM(Long Short-Term Memory)

mysql同一个表中相同数据怎么合并

部署jar包
随机推荐
ansible playbook语法和格式 自动化云计算
第三章 启用和调整IM列存储的大小(IM-3.1)
[untitled]
454、四数之和(哈希表)
What are Jerry's usual program exceptions? [chapter]
一文看懂 LSTM(Long Short-Term Memory)
ansible 云计算 自动化
景联文科技—专业数据标注公司和智能数据标注平台
LeetCode-608. Tree node
C language - custom type
深度选择器
203. Remove linked list elements (linked list)
Jerry's users how to handle events in the simplest way [chapter]
DBA常用SQL语句 (5) - Latch 相关
MapReduce compression
DBA common SQL statements (3) - cache, undo, index and wait events
Arbitrary file reading vulnerability exploitation Guide
59、螺旋矩阵(数组)
Swagger2 自定义参数注解如何不显示
定义链表(链表)
