【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;
    }  
    }
相关推荐
fTiN CAPA6 分钟前
Linux系统离线部署MySQL详细教程(带每步骤图文教程)
linux·mysql·adb
黎阳之光9 分钟前
全域实景立体管控:数字孪生与视频孪生技术体系白皮书
大数据·人工智能·算法·安全·数字孪生
88号技师1 小时前
2026年4月一区SCI-狒狒优化算法Baboon optimization algorithm-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
xlq223221 小时前
52.TcpSocket
linux·服务器·网络
剑神一笑1 小时前
Linux xargs 命令深度解析:从管道到命令构建的桥梁
linux·运维·chrome
凯瑟琳.奥古斯特1 小时前
BFS解力扣1654最短跳跃次数
数据结构·算法·广度优先
sg_knight1 小时前
第一次用 OpenClaw,我让它 3 分钟写了个小工具
算法·llm·agent·ai编程·openclaw
m0_629494731 小时前
LeetCode 热题 100-----23.反转链表
数据结构·算法·leetcode·链表
炸膛坦客1 小时前
嵌入式 - 数据结构与算法:(1-10)排序算法 - 冒泡排序(Bubble Sort)
算法·排序算法
Hello eveybody1 小时前
介绍一下动态树LCT(Python)
开发语言·python·算法