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
};
相关推荐
To_OC8 小时前
LC 51 N 皇后:我以为难的是回溯,结果栽在了对角线下标
javascript·算法·leetcode
2401_841495648 小时前
【操作系统】进程同步与互斥实验报告
c++·算法·操作系统·进程·并发·同步·互斥
爱刷碗的苏泓舒12 小时前
PPP-AR 中的参考星选取:数学原理、评价指标与切换处理
算法·gnss·模糊度固定·ppp-ar·星间单差·参考星·卫星端偏差
烬羽15 小时前
递归老写崩?一个"退回"公式,把回溯题变成填空题
javascript·深度学习·算法
闪电悠米15 小时前
力扣hot100-41.缺失的第一个正数-原地哈希详解
数据结构·算法·哈希算法
WL学习笔记16 小时前
堆(数据结构)
数据结构·
星空露珠16 小时前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
QXWZ_IA17 小时前
桥梁数字孪生怎么落地?
人工智能·科技·算法·智能硬件·政务
Kel17 小时前
输出层与反分词(Output Layer & Detokenization)
人工智能·算法·架构