【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 分钟前
第十一章 构建基本脚本
linux
星恒随风27 分钟前
从0实现C++ AI大模型接入SDK(二):AI知识科普——从图灵测试到ChatGPT,人工智能的发展历程
linux·c++·人工智能·笔记·chatgpt
飞奔的瓜牛29 分钟前
Linux 数据盘分区、格式化与自动挂载完整实践
linux·运维·服务器
青少儿编程课堂40 分钟前
蓝桥杯真题解析:三维偏序的CDQ分治(全国青少年信息素养大赛与电子学会编程考级)
c++·python·算法·bfs·信息学竞赛
Navigator_Z1 小时前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
geovindu1 小时前
python:Lasso
开发语言·后端·python·算法
Lucas. Wáng2 小时前
Linux网络编程之网络套接字
linux·服务器·网络
AAA修煤气灶刘哥2 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
进击的荆棘2 小时前
Linux网络——Socket编程TCP
linux·运维·服务器·网络·tcp/ip
大今野3 小时前
2026 专转本计算机|Linux CentOS7 软件包管理:yum 仓库配置与常用命令考点全解(附例题)
linux·运维·服务器·专转本