【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;
    }  
    }
相关推荐
z200509306 分钟前
今日算法(依旧二叉树)
算法·leetcode·职场和发展
开发者联盟league6 分钟前
linux普通用户使用pip安装模块
linux·python·pip
QuestLab9 分钟前
③-进阶篇:vLLM实战——多卡部署、压测与排障
linux·服务器·网络
Languorous.16 分钟前
Windows 安装 Linux 虚拟机 / WSL 完整教程(新手零失败)
linux·运维·windows
Zxc_23 分钟前
《遗传算法:从自然选择到Rastrigin函数优化,手写一个完整的进化求解器》
算法
阿Y加油吧37 分钟前
两道经典动态规划题:乘积最大子数组 & 分割等和子集 复盘笔记
笔记·算法·动态规划
三品吉他手会点灯1 小时前
C语言学习笔记 - 33.数据类型 - printf函数的详细用法
c语言·开发语言·笔记·学习·算法
颂love1 小时前
Linux命令的简单学习
linux·运维·学习
NashSKY2 小时前
PnP 问题:数学描述与 DLT 算法推导
算法·矩阵分解·多视图几何·射影几何
satadriver2 小时前
ip-guard网络通信加解密
linux·网络·tcp/ip