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
};
相关推荐
真的想上岸啊11 分钟前
c语言第一个小游戏:贪吃蛇小游戏05
c语言·算法·链表
元亓亓亓35 分钟前
LeetCode热题100--206.反转链表--简单
算法·leetcode·链表
边跑边掩护40 分钟前
LeetCode 373 查找和最小的 K 对数字题解
leetcode
诚丞成1 小时前
BFS算法篇——从晨曦到星辰,BFS算法在多源最短路径问题中的诗意航行(上)
java·算法·宽度优先
hongjianMa1 小时前
2024睿抗编程赛国赛-题解
算法·深度优先·图论·caip
czy87874751 小时前
两种常见的C语言实现64位无符号整数乘以64位无符号整数的实现方法
c语言·算法
想睡hhh1 小时前
c++进阶——哈希表的实现
开发语言·数据结构·c++·散列表·哈希
yzx9910131 小时前
支持向量机案例
算法·机器学习·支持向量机
天上路人2 小时前
采用AI神经网络降噪算法的语言降噪消回音处理芯片NR2049-P
深度学习·神经网络·算法·硬件架构·音视频·实时音视频·可用性测试
chao_7892 小时前
手撕算法(定制整理版2)
笔记·算法