【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;
    }  
    }
相关推荐
啊董dong2 分钟前
noi-2026年1月07号作业
数据结构·c++·算法·noi
嘿嘿潶黑黑16 分钟前
Linux 安装 Qt
linux·qt
大聪明-PLUS23 分钟前
Linux进程间通信(IPC)指南 - 第3部分
linux·嵌入式·arm·smarc
l1t25 分钟前
DeepSeek辅助编写的利用唯一可选数求解数独SQL
数据库·sql·算法·postgresql
水天需01034 分钟前
Linux 空操作详解
linux
WJSKad12351 小时前
传送带物体检测识别_基于YOLO11与RGCSPELAN改进算法_工业视觉检测系统
人工智能·算法·视觉检测
被遗忘的旋律.1 小时前
Linux驱动开发笔记(二十三)—— regmap
linux·驱动开发·笔记
RisunJan1 小时前
Linux命令-iotop命令(实时磁盘 I/O 监控工具)
linux·运维·服务器
仍然.1 小时前
JavaDataStructure---排序
数据结构·算法·排序算法
XMYX-01 小时前
CentOS 7 搭建 PostgreSQL 14 实战指南
linux·postgresql·centos