力扣 102. 二叉树的层序遍历
题目
给你二叉树的根节点 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
解
这道题题目的意图已经够明显了吧,妥妥的BFS
不过根据要求的输出的格式,需要维护两个数组
- 时间复杂度
O(n)
- 空间复杂度
O(n)
/**
* 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) {
// bfs
let res = [];
if(!root) return res;
let q = [root];
while(q.length) {
let curLength = q.length;
res.push([]);
while(curLength--) {
let node = q.shift();
res[res.length - 1].push(node.val);
node.left && q.push(node.left);
node.right && q.push(node.right);
}
}
return res;
};
仅供参考