【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;
    }  
    }
相关推荐
雪落漂泊几秒前
Linux进程(三)概念:进程优先级与进程切换篇
linux·运维·服务器
拂拉氏1 分钟前
【知识讲解】 Linux信号与可重入函数的认识
linux·运维·服务器
cynicism??7 分钟前
Linux 与 ZXISOS 驱动开发架构对比
linux·驱动开发·架构
郝学胜-神的一滴9 分钟前
游戏设计:原型与开发 19:U3D工位布置与性格说明书
人工智能·算法·unity·unreal engine·游戏策划·游戏设计
djjjx.17 分钟前
Linux进程篇(十二):从零构建属于你的自定义 Shell 解释器
linux·运维·服务器
hahaha60161 小时前
数字图像时域滤波或者3D降噪算法FPGA实现
算法·计算机视觉·fpga开发
文丑颜不良啊1 小时前
LeetCode1541~1560题目解析
java·leetcode
YSL0701241 小时前
一文通关-----树和二叉树
数据结构·算法
青少儿编程课堂1 小时前
蓝桥杯青少组图形化+信息素养+电子学会Scratch考级:校园口算闯关解析
c++·python·算法·bfs·信息学竞赛
computersciencer1 小时前
应用贝叶斯公式:迟到了,那坐的是哪种交通工具呢?
算法·机器学习·概率论