【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;
    }  
    }
相关推荐
社交怪人2 分钟前
【判断大小】信息学奥赛一本通C语言解法(题号1043)
算法
Snasph16 分钟前
GNU Make 用户手册(中文版)
服务器·算法·gnu
江澎涌42 分钟前
拆解与 AI 的一次对话
人工智能·算法·程序员
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2026.06.02 题目:3635. 最早完成陆地和水上游乐设施的时间 II
笔记·算法·leetcode
Lsk_Smion1 小时前
力扣实训 _ [102].层序遍历--前序--后续_递归与非递归的实现
数据结构·算法·leetcode
kTR2hD1qb2 小时前
从 Responses API 到 Chat Completions:一个模型网关的设计复盘
linux·前端
姓刘的哦2 小时前
大模型祛魅
linux
小欣加油3 小时前
leetcode3751 范围内总波动值I
java·数据结构·c++·算法·leetcode
hj2862513 小时前
linux下一步学习内容
linux·运维
Halo_tjn4 小时前
反射与设计模式1
java·开发语言·算法