当前位置:网站首页>【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
边栏推荐
猜你喜欢
MapReduce core and foundation demo
Arm debugging (1): two methods to redirect printf to serial port in keil
101. Symmetric Tree
101. Symmetric Tree
shell脚本免交互
部署jar包
Yarn core parameter configuration
【无标题】
Reading integrity monitoring techniques for vision navigation systems - 3 background
Jerry's more accurate determination of abnormal address [chapter]
随机推荐
Solve the problem of installing VMware after uninstalling
142. Circular linked list||
Operation of 2022 tea artist (primary) test question simulation test platform
通过流式数据集成实现数据价值(2)
DBA common SQL statements (5) - latch related
CentOS/Linux安装MySQL
C language - custom type
mysql同一个表中相同数据怎么合并
/Can etc / shadow be cracked?
/etc/shadow可以破解吗?
二叉树的构建和遍历
【无标题】
Swagger2 自定义参数注解如何不显示
Chapter 1 Oracle database in memory related concepts (im-1.1)
一文看懂 LSTM(Long Short-Term Memory)
定义链表(链表)
2022 mobile crane driver test question bank simulation test platform operation
Linked list intersection (linked list)
微信小程序中app.js文件、组件、api
Realize data value through streaming data integration (1)