102. 二叉树的层序遍历

82 字
1 分钟
102. 二叉树的层序遍历

思路就是用BFS(广度优先遍历),用嵌套数组携带层级信息用于判断是哪一层

var levelOrder = function (root) {
if(!root) return []
const res = []
const queue = [[root, 0]]
while(queue.length) {
const [ node, level ] = queue.pop()
if(res[level]) {
res[level].push(node.val)
} else {
res[level] = [node.val]
}
if(node.right) queue.push([node.right, level + 1])
if(node.left) queue.push([node.left, level + 1])
}
return res
};

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

102. 二叉树的层序遍历
https://an2333.com/posts/basic/algorithm/tree/102二叉树的层序遍历/
作者
Annan
发布于
2025-05-21
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
Annan
写点前端,聊点 AI。
公告
博客已迁移到 Astro + Firefly,旧文章正在陆续搬家中。
分类
标签
站点统计
文章
50
分类
7
标签
28
总字数
84,160
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
GitHub Actions
博客版本
Firefly v6.16.8
文章许可
CC BY-NC-SA 4.0

当前页面没有目录

文章目录

当前页面没有目录