LeetCode 102. 二叉树的层序遍历
作者:Choi Yang
更新于:17 小时前
字数统计:262 字
阅读时长:1 分钟
题目描述
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
javascript
二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7返回其层次遍历结果:
javascript
[[3], [9, 20], [15, 7]]来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
直接用 BFS,对于每一层初始化空数组,然后存放每一层的节点值,然后迭代即可。
javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
function levelOrder(root) {
if (!root)
return []
const res = []
const queue = [root]
let cnt = 0
while (queue.length) {
let size = queue.length
// 每一层初始化一个空数组
res.push([])
while (size--) {
const node = queue.shift()
// 每一层的节点都存着
res[cnt].push(node.val)
node.left && queue.push(node.left)
node.right && queue.push(node.right)
}
// 迭代层次
++cnt
}
return res
}javascript
学如逆水行舟,不进则退Contributors
文章作者:Choi Yang
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 ChoDocs!
