【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;
    }  
    }
相关推荐
Trent19851 小时前
影楼精修-肤色统一算法解析
图像处理·人工智能·算法·计算机视觉
feifeigo1231 小时前
高光谱遥感图像处理之数据分类的fcm算法
图像处理·算法·分类
qq_339282232 小时前
centos中libc.so.6No such file的解决方式
linux·运维·centos
leoufung2 小时前
ECPF 简介
linux·网络·kernel
北上ing2 小时前
算法练习:19.JZ29 顺时针打印矩阵
算法·leetcode·矩阵
在肯德基吃麻辣烫3 小时前
Netdata在Ubuntu环境下的安装与配置:构建实时系统监控与性能分析平台
linux·运维·ubuntu
.格子衫.3 小时前
真题卷001——算法备赛
算法
XiaoyaoCarter3 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树
Hygge-star4 小时前
【数据结构】二分查找5.12
java·数据结构·程序人生·算法·学习方法
愚戏师4 小时前
Linux复习笔记(六)shell编程
linux·笔记·shell