【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;
    }  
    }
相关推荐
Yang_jie_0334 分钟前
笔记:数据结构(栈是否使用底指针以及头指针的初始化值)
数据结构·笔记·算法
2301_800895101 小时前
信息安全数学基础复习
算法
爱折腾的小黑牛1 小时前
简记往来批量录入功能的实现:从文本到结构化数据
前端·算法
qetfw1 小时前
CentOS 7 基础环境配置
linux·运维·centos
Starmoon_dhw1 小时前
题解:P17078 夏日甜点
c++·学习·算法·图论
天空'之城1 小时前
Linux 系统编程 21:守护进程与日志系统全解
linux·系统编程·日志系统·守护进程
海石2 小时前
【JS击败90%】前缀和+定长滑动窗口
算法·leetcode
l1t2 小时前
用split命令恢复被wget -c命令误追加的zip压缩包
linux
Tisfy2 小时前
LeetCode 2685.统计完全连通分量的数量:DFS求每个连通块的边点数
算法·leetcode·深度优先··题解·连通图·全连通分量
海石2 小时前
1次遍历,空间复杂度击败100%,时间复杂度击败85%
算法·leetcode