【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;
    }  
    }
相关推荐
辰风沐阳1 小时前
nvm - node 版本管理工具【macOS/Linux】
linux·运维·macos
君穆南8 小时前
基于 NFS 与 Rsync 实现跨服务器 Seafile 数据平滑迁移实战
linux·运维·git
bloglin999998 小时前
scp、rsync远程文件同步
linux·运维·服务器
迦南的迦 亚索的索8 小时前
LINUX环境
linux·运维·服务器
yuanjj888 小时前
linux下调试域格CLM920 NC5等9x07平台模块 QMI拨号
linux·运维·服务器
IMPYLH9 小时前
Linux 的 printenv 命令
linux·运维·服务器·bash
SilentSamsara9 小时前
SSH 远程管理:密钥登录 + 隧道转发,一次性配置好
linux·运维·服务器·ubuntu·centos·ssh
LN花开富贵9 小时前
【ROS】鱼香ROS2学习笔记一
linux·笔记·python·学习·嵌入式·ros·agv
疏星浅月9 小时前
数据对齐的底层原理与性能优化
linux
Jurio.9 小时前
本机开发 + 多机执行的极简远端运行工具
linux·git·python·github·远程工作