【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;
    }  
    }
相关推荐
新时代牛马5 小时前
Linux 守护进程与服务完整篇:从daemonize、systemd 到pidfile 与排障
linux·运维·服务器
phltxy14 小时前
C语言操作符详解
java·c语言·算法
aqiu11111115 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
徐小黑ACG15 小时前
nginx配置文件
linux·服务器·nginx
新时代牛马15 小时前
Linux VFS 完整篇:从path_openat、dentry/inode 到page cache 与挂载排障
linux·运维·服务器
辰烨chenye15 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
java_logo15 小时前
Docker 部署 Rocky Linux:轻松搭建 RHEL 兼容企业级基础镜像平台
linux·docker·容器·rocky linux·基础镜像·轩辕镜像·rhel 兼容
拂拉氏16 小时前
【知识讲解】 Linux虚拟地址空间认识
linux·虚拟地址空间
罗西的思考16 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习