【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;
    }  
    }
相关推荐
女神下凡5 分钟前
芯参谋(131):山景(MVsilicon)_开发指南
linux·arm开发·stm32·单片机·嵌入式硬件
地平线开发者1 小时前
查帧率、看负载、开日志:hrut_camsys 的 J6X Camsys 调试日常
linux·自动驾驶
星恒随风1 小时前
从0实现C++ AI大模型接入SDK(五):DeepSeekProvider的实现——策略模式、HTTP请求与SSE流式响应
linux·开发语言·c++·人工智能
weixin_404679311 小时前
cc 在 linux 安装
linux·运维·服务器
xckkcxxck1 小时前
Kaggle S6E10 冠军方案精读(二):245 个模型的合唱团,和一个只会“线性指挥“的老师
算法
饮水桶_T2 小时前
Git笔记
开发语言·笔记·算法
指掀涛澜天下惊2 小时前
强化学习进阶篇十四 DPO算法
深度学习·算法·机器学习·sft·预训练·dpo
小宋10214 小时前
embedding 返回全零向量,索引却照收不误:入库前的向量健康门禁、隔离重算与召回恢复判据
linux·服务器·网络·人工智能
重生之小比特4 小时前
【Linux系统】22 线程概念与控制(上)
linux·运维
AAA修煤气灶刘哥4 小时前
我都切到下一张图了,Agent 怎么还在解释上一张?
人工智能·算法·架构