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
};
相关推荐
charliejohn1 小时前
计算机考研 408 数据结构 树形查找 相关概念及计算题例题
数据结构·考研
NAGNIP6 小时前
一文搞懂机器学习中的特征降维!
算法·面试
NAGNIP7 小时前
一文搞懂机器学习中的特征构造!
算法·面试
Learn Beyond Limits7 小时前
解构语义:从词向量到神经分类|Decoding Semantics: Word Vectors and Neural Classification
人工智能·算法·机器学习·ai·分类·数据挖掘·nlp
你怎么知道我是队长7 小时前
C语言---typedef
c语言·c++·算法
Qhumaing9 小时前
C++学习:【PTA】数据结构 7-1 实验7-1(最小生成树-Prim算法)
c++·学习·算法
踩坑记录10 小时前
leetcode hot100 3.无重复字符的最长子串 medium 滑动窗口(双指针)
python·leetcode
Z1Jxxx10 小时前
01序列01序列
开发语言·c++·算法
汽车仪器仪表相关领域12 小时前
全自动化精准检测,赋能高效年检——NHD-6108全自动远、近光检测仪项目实战分享
大数据·人工智能·功能测试·算法·安全·自动化·压力测试