当前位置:网站首页>【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
边栏推荐
猜你喜欢
随机推荐
【省选联考 2022 D2T1】卡牌(状态压缩 DP,FWT卷积)
Sim Api User Guide(8)
【无标题】
Realizing data value through streaming data integration (4) - streaming data pipeline
997、有序数组的平方(数组)
Arbitrary file reading vulnerability exploitation Guide
转:毛姆:阅读是一座随身携带的避难所
Contact between domain name and IP address
景联文科技—专业数据标注公司和智能数据标注平台
LeetCode-608. 树节点
LeetCode-608. Tree node
Configuration of LNMP
SQL Server 游标循环表数据
IDEA——》每次启动都会Indexing或 scanning files to index
/etc/shadow可以破解吗?
CSP认证 202203-2 出行计划(多种解法)
Sim Api User Guide(5)
Jinglianwen technology - professional data annotation company and intelligent data annotation platform
206、反转链表(链表)
精彩回顾 | DEEPNOVA x Iceberg Meetup Online《基于Iceberg打造实时数据湖》







