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
};
相关推荐
JCBP_2 分钟前
QT(4)
开发语言·汇编·c++·qt·算法
码熔burning6 分钟前
JVM 垃圾收集算法详解!
jvm·算法
小柴狗28 分钟前
C语言关键字详解:static、const、volatile
算法
仙俊红2 小时前
LeetCode每日一题,20250914
算法·leetcode·职场和发展
风中的微尘9 小时前
39.网络流入门
开发语言·网络·c++·算法
西红柿维生素10 小时前
JVM相关总结
java·jvm·算法
ChillJavaGuy12 小时前
常见限流算法详解与对比
java·算法·限流算法
散11212 小时前
01数据结构-01背包问题
数据结构
sali-tec12 小时前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
消失的旧时光-194312 小时前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack