【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;
    }  
    }
相关推荐
YuanDaima204814 小时前
双指针基础原理与题目说明
数据结构·人工智能·python·算法·leetcode·手撕代码
别或许14 小时前
5、高数----一元函数微分学的应用(一)几何应用
算法
默|笙14 小时前
【Linux】线程互斥与同步_同步(2)_环形队列
linux·运维·服务器
wayz1114 小时前
Day 5:KNN算法与相似K线匹配
人工智能·算法·机器学习
cui_ruicheng14 小时前
Linux IO入门(一):从C语言IO到文件描述符
linux·运维·c语言
丸子家的银河龙14 小时前
yocto使用实例[1]-自定义内核配方
linux
晨曦中的暮雨14 小时前
Java集合类型主要有哪些?以及各自原理
数据结构·算法
Wenweno0o14 小时前
CC-Switch & Claude 基于 Linux 服务器安装使用指南
linux·服务器·claude code·cc-switch
lixinnnn.15 小时前
01BFS:Three States
算法
晓纪同学15 小时前
EffctiveC++_第三章_资源管理
开发语言·c++·算法