【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;
    }  
    }
相关推荐
maosheng11463 小时前
RHCSA的第一次作业
linux·运维·服务器
wifi chicken3 小时前
Linux 端口扫描及拓展
linux·端口扫描·网络攻击
旺仔.2913 小时前
Linux 信号详解
linux·运维·网络
放飞梦想C3 小时前
CPU Cache
linux·cache
I_LPL3 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱4 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
Hoshino.414 小时前
基于Linux中的数据库操作——下载与安装(1)
linux·运维·数据库
WolfGang0073214 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
2401_831824965 小时前
代码性能剖析工具
开发语言·c++·算法
播播资源6 小时前
CentOS系统 + 宝塔面板 部署 OpenClaw源码开发版完整教程
linux·运维·centos