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
};
相关推荐
YGGP33 分钟前
【Golang】LeetCode 128. 最长连续序列
leetcode
你撅嘴真丑7 小时前
第九章-数字三角形
算法
uesowys7 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder7 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮7 小时前
AI 视觉连载1:像素
算法
智驱力人工智能8 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
孞㐑¥8 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
月挽清风8 小时前
代码随想录第十五天
数据结构·算法·leetcode
XX風9 小时前
8.1 PFH&&FPFH
图像处理·算法
NEXT069 小时前
前端算法:从 O(n²) 到 O(n),列表转树的极致优化
前端·数据结构·算法