【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 小时前
7大推荐系统/算法框架对比
算法·推荐算法
sorry#1 小时前
top简单使用
linux·运维
adam-liu1 小时前
Fun Audio Chat 论文+项目调研
算法·语音端到端·fun-audio-chat
栀秋6661 小时前
你会先找行还是直接拍平?两种二分策略你Pick哪个?
前端·javascript·算法
如果你想拥有什么先让自己配得上拥有1 小时前
数学思想和数学思维分别都有什么?
线性代数·算法·机器学习
QQ__17646198242 小时前
Ubuntu系统创建新用户与删除用户
linux·运维·服务器
长安er2 小时前
LeetCode136/169/75/31/287 算法技巧题核心笔记
数据结构·算法·leetcode·链表·双指针
MarkHD2 小时前
智能体在车联网中的应用:第29天 多智能体完全合作场景的核心算法:从CTDE思想到VDN与MADDPG的深度解析
算法
渣渣盟2 小时前
Linux邮件服务器快速搭建指南
linux·服务器·开发语言
6极地诈唬2 小时前
【PG漫步】DELETE不会改变本地文件的大小,VACUUM也不会
linux·服务器·数据库