leetcode429-N叉树的层序遍历

leetcode 429

思路

这里n叉树的层序遍历和二叉树的层序遍历非常相似,可以参考博文:二叉树的层序遍历

N叉树对比二叉树就是有多个孩子节点,二叉树是有一个left和一个right节点,n叉树因为有多个子节点,所以通过children来存放所有的孩子节点,然后在层级遍历的时候,要遍历children中的所有元素入队列

可能一开始看到题目的时候不太明白构造出来的二叉树和N叉树的一个数据结构,下面模拟一下构造逻辑

二叉树的构造
js 复制代码
class TreeNode {
  constructor(val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

const root = new TreeNode(5)
root.left = new TreeNode(4)
root.right = new TreeNode(6)
root.left.left = new TreeNode(1)
root.left.right = new TreeNode(2)
N叉树的构造
js 复制代码
class TreeNode {
  constructor(val) {
    this.val = val;
    this.children = null
  }
}

const root = new TreeNode(1)
root.children = [new TreeNode(3),new TreeNode(2),new TreeNode(4)]
root.children[0].children = [new TreeNode(5),new TreeNode(6)]

实现

js 复制代码
var levelOrder = function (root) {
    if (!root) return [];
    let result = [], queue = [root];
    while (queue.length) {
        let len = queue.length;
        let arr = [];
        while (len--) {
            let node = queue.shift();
            arr.push(node.val);
            if (node.children) {
                for (const item of node.children) {
                    queue.push(item)
                }
            }
        }
        result.push(arr)
    }
    return result
};
相关推荐
木木_王5 分钟前
嵌入式Linux学习 | 数据结构 (Day05) 栈与队列详解(原理 + C 语言实现 + 实战实验 + 易错点剖析)
linux·c语言·开发语言·数据结构·笔记·学习
北顾笙98024 分钟前
day38-数据结构力扣
数据结构·算法·leetcode
m0_6294947325 分钟前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
xin_nai29 分钟前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展
旖-旎39 分钟前
深搜练习(组合)(5)
c++·算法·深度优先·力扣
@小码农1 小时前
2026年3月Scratch图形化编程等级考试一级真题试卷
开发语言·数据结构·c++·算法
Wect2 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·算法·typescript
糖果店的幽灵2 小时前
决策树详解与sklearn实战
算法·决策树·sklearn
Lewiis2 小时前
趣谈排序算法
算法·排序算法
ComputerInBook2 小时前
数字图像处理(4版)——第 8 章——图像压缩与水印(上)(Rafael C.Gonzalez&Richard E. Woods)
人工智能·算法·计算机视觉·图像压缩·图像水印