题目:
题目截图:
解题步骤:
1.广度优先遍历二叉树
2.遍历过程中,记录每个节点的层级,并将其添加到不同的数组中
代码:
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
if (!root) return [];
const q = [root];
const res = [];
while (q.length) {
let len = q.length;
res.push([]);
// 下面这个while循环,每结束一次,里面就只是同一级的值,非常巧妙
while (len--) {
const n = q.shift();
res[res.length - 1].push(n.val);
if (n.left) q.push(n.left);
if (n.right) q.push(n.right);
}
}
return res;
};
时间复杂度分析:
时间复杂度是O(n),n是二叉树的节点个数
空间复杂度分析:
空间复杂度是O(n)
怎么样,是不是很简单,你学会了吗 ?
如果这篇文章能够帮助到您,希望您不要吝惜点赞👍👍和收藏💖💖,您的支持是我继续努力的动力 💪💪 !!!