【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;
    }  
    }
相关推荐
wearegogog1233 分钟前
光伏发电系统最大功率跟踪(MPPT)算法 Matlab 实现指南
开发语言·算法·matlab
Tisfy3 分钟前
LeetCode 3783.整数的镜像距离:数学
数学·算法·leetcode·题解
水蓝烟雨5 分钟前
0010.三数之和
数据结构·算法·leetcode
啥咕啦呛16 分钟前
跟着AI学Java第2天:Java基础语法巩固
java·python·算法
北山有鸟31 分钟前
相机的水平消隐与垂直消隐
linux·驱动开发·相机
还不秃顶的计科生32 分钟前
多模态模型下载
java·linux·前端
无忧.芙桃40 分钟前
进程控制之进程等待
linux·运维·服务器
csuzhucong1 小时前
螺旋归纳DP
算法
云栖梦泽1 小时前
Linux内核与驱动:13.从设备树到Platform平台总线
linux·运维·c++·嵌入式硬件
qeen871 小时前
【算法笔记】模拟与高精度加减乘除
c++·笔记·算法·高精度·模拟