【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;
    }  
    }
相关推荐
哈里谢顿9 分钟前
环境变量 HTTP_PROXY/HTTPS_PROXY 深度解析:为什么 cURL 行,Docker 不行?
linux
curry____30310 分钟前
基本算法(2025.11.21)
c++·算法
馨谙20 分钟前
使用 systemd 用户服务管理容器:从概念到实践
linux·容器
人工智能训练40 分钟前
Windows中如何将Docker安装在E盘并将Docker的镜像和容器存储在E盘的安装目录下
linux·运维·前端·人工智能·windows·docker·容器
zzzsde1 小时前
【Linux】基础开发工具(1):软件包管理器&&vim编辑器
linux·运维·服务器
tan180°1 小时前
Linux网络TCP(上)(11)
linux·网络·c++·后端·tcp/ip
WWZZ20251 小时前
快速上手大模型:深度学习5(实践:过、欠拟合)
人工智能·深度学习·神经网络·算法·机器人·大模型·具身智能
断水客1 小时前
如何在手机上搭建Linux学习环境
linux·运维·学习
会飞的土拨鼠呀1 小时前
ubuntu24安装snmp服务
linux·运维
胖好白1 小时前
【RK3588开发】模型部署全流程
linux·人工智能