【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;
    }  
    }
相关推荐
迷途之人不知返3 分钟前
shell相关知识与Linux权限
linux
赵域Phoenix7 分钟前
混沌系统是什么?
人工智能·算法·机器学习
SPC的存折7 分钟前
3、主从复制实现同步数据过滤
linux·运维·服务器
SPC的存折9 分钟前
openEuler 24.03 MariaDB Galera 集群部署指南(cz)
linux·运维·服务器·数据库·mysql
CoderCodingNo11 分钟前
【GESP】C++五、六级练习题 luogu-P1886 【模板】单调队列 / 滑动窗口
开发语言·c++·算法
paeamecium13 分钟前
【PAT甲级真题】- All Roads Lead to Rome (30)
数据结构·c++·算法·pat考试·pat
Cando学算法19 分钟前
双指针之快慢指针
算法
SPC的存折22 分钟前
MySQL 8.0 分库分表
linux·运维·服务器·数据库·mysql
汀、人工智能27 分钟前
[特殊字符] 第100课:任务调度器
数据结构·算法·数据库架构·贪心··任务调度器
每日任务(希望进OD版)29 分钟前
二分法刷题
算法·二分