【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;
    }  
    }
相关推荐
brave_zhao16 分钟前
openEuler下安装tar包解压工具
linux·服务器·数据库
QN1幻化引擎18 分钟前
Dalin L — 我造了一门支持中文编程的语言,完整移植到 Rust 了
人工智能·算法·机器学习
Rainy Blue88319 分钟前
C转C++速成
c语言·c++·算法
小宏运维有点菜24 分钟前
JumpServer
linux·运维
txzrxz31 分钟前
二分图详解
数据结构·c++·算法·图论·深度优先搜索·二分图染色
gaosushexiangji1 小时前
数字图像相关DIC系统在结构振动模态测量中的应用
算法
是个西兰花1 小时前
Linux:死锁与生产者消费者模型解析
linux·运维·服务器·c++·死锁·生产者消费者模型
KaMeidebaby1 小时前
卡梅德生物技术快报|如何制备单克隆抗体:小众禽类靶点单抗制备实操流程:双载体抗原交叉筛选完整工艺记录
人工智能·python·深度学习·算法·机器学习
RisunJan1 小时前
Linux命令-rsync(远程/本地文件同步 —— 增量传输的备份与镜像神器)
linux·运维·服务器
爆浇牛肉面2 小时前
Linux进阶命令:测开必学的curl和jq
linux