【LeetCode-中等题】429. N 叉树的层序遍历

文章目录

题目

方法一:二叉树的层序遍历的扩展

思路和二叉树的层序遍历一样,这一题的关键在于取出每个节点的孩子

java 复制代码
for(int j = 0;j<root.children.size();j++)//取出所有当前节点的所有孩子节点放到队列中
    queue.offer(root.children.get(j));
或者
for(Node node:root.children)//取出所有当前节点的所有孩子节点放到队列中
    queue.offer(node);
java 复制代码
class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        List<Integer> res = null;
        List<List<Integer>> zres = new ArrayList<>();
            if(root == null) return zres;
            Deque<Node> queue = new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()){
                    int size = queue.size();
                    res = new ArrayList<>();
                    for(int i =0;i<size;i++){
                        root=queue.poll();
                        res.add(root.val);
                        for(int j = 0;j<root.children.size();j++)//取出所有当前节点的所有孩子节点放到队列中
                            queue.offer(root.children.get(j));
                    }
                    zres.add(res);
            }
            return zres;
    }  
    }
相关推荐
Godspeed Zhao3 分钟前
从零开始学AI16——SVM
算法·机器学习·支持向量机
江屿风14 分钟前
C++OJ题经验总结(竞赛)1
开发语言·c++·笔记·算法
nebula-AI16 分钟前
人工智能导论:模型与算法(核心技术)
人工智能·深度学习·神经网络·算法·机器学习·集成学习·sklearn
运筹vivo@34 分钟前
LeetCode 2405. 子字符串的最优划分
c++·算法·leetcode·职场和发展·哈希表
数智工坊34 分钟前
视觉-语言-动作模型解剖学:从模块、里程碑到核心挑战
论文阅读·人工智能·深度学习·算法·transformer
有点。1 小时前
C++(枚举法一练习题)
开发语言·c++·算法
黎阳之光1 小时前
视听融合新范式!黎阳之光打破视觉边界,声影协同赋能全域智慧管控
大数据·人工智能·物联网·算法·数字孪生
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2026.05.19 题目:2540. 最小公共值
笔记·leetcode·排序算法
玖釉-2 小时前
栈——栈的定义及基本操作
c++·windows·算法·图形渲染
LN花开富贵2 小时前
Ubuntu aarch64 架构安装 NoMachine 远程控制 避坑与实战
linux·运维·笔记·学习·ubuntu·嵌入式