当前位置:网站首页>【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
边栏推荐
猜你喜欢
Example of pop-up task progress bar function based on pyqt5
【无标题】
Examination questions and answers of the third batch (main person in charge) of Guangdong safety officer a certificate in 2022
基于PyQt5实现弹出任务进度条功能示例
JVM——》常用参数
Six practices of Windows operating system security attack and defense
得到知识服务app原型设计比较与实践
lnmp的配置
JUC concurrent programming 06 -- in-depth analysis of AQS source code of queue synchronizer
Shell script interaction free
随机推荐
Configuration of LNMP
Sim Api User Guide(4)
Six practices of Windows operating system security attack and defense
二叉树的构建和遍历
MySql常用语句
Windows installs redis and sets the redis service to start automatically
第一章 Oracle Database In-Memory 相关概念(IM-1.1)
C语言——自定义类型
LeetCode-608. 树节点
深度选择器
349、两个数组的交集
C language - custom type
Realize data value through streaming data integration (1)
通过流式数据集成实现数据价值(5)- 流分析
What are the system events of Jerry's [chapter]
Jerry's users how to handle events in the simplest way [chapter]
Realize data value through streaming data integration (3) - real-time continuous data collection
第120章 SQL函数 ROUND
Sim Api User Guide(5)
Initial exploration of NVIDIA's latest 3D reconstruction technology instant NGP