【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;
    }  
    }
相关推荐
爱睡懒觉的焦糖玛奇朵1 小时前
【从视频到数据集:焦糖玛奇朵的魔法工具使用说明】
人工智能·python·深度学习·学习·算法·yolo·音视频
广州灵眸科技有限公司1 小时前
瑞芯微(EASY EAI)RV1126B 核心板供电电路
linux·运维·服务器·单片机·嵌入式硬件·电脑
keyipatience1 小时前
18.Linux进程退出和进程等待机制详解
linux·运维·服务器
Runawayliquor1 小时前
opbase:CANN 所有算子的公共地基
大数据·数据库·人工智能·算法
徐安安ye1 小时前
FlashAttention 为什么对序列长度这么“敏感”?
人工智能·算法
齐齐大魔王2 小时前
Linux-网络编程实战
linux·运维·网络
花阴偷移3 小时前
Ubuntu 22.04版本下配置静态IP
linux·运维·服务器·tcp/ip·ubuntu
weixin_473437233 小时前
Swift4D处理Multi-view dataset记录
linux
黎阳之光3 小时前
黎阳之光:以视频孪生重构智能监盘,为燃机打造新一代智慧电厂大脑
大数据·人工智能·算法·安全·数字孪生
绝知此事3 小时前
【算法突围 02】树形结构与数据库索引:树形结构与数据库索引:从 BST 到 B+ 树的演化与 MySQL 优化
数据库·mysql·算法·面试·b+树