【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;
    }  
    }
相关推荐
鲨莎分不晴29 分钟前
【前沿技术】Offline RL 全解:当强化学习失去“试错”的权利
人工智能·算法·机器学习
刘某的Cloud1 小时前
列表、元组、字典、集合-组合数据类型
linux·开发语言·python
学烹饪的小胡桃1 小时前
【运维学习】实时性能监控工具 WGCLOUD v3.6.2 更新介绍
linux·运维·服务器·学习·工单系统
XFF不秃头1 小时前
力扣刷题笔记-全排列
c++·笔记·算法·leetcode
知识分享小能手1 小时前
Ubuntu入门学习教程,从入门到精通,Ubuntu 22.04的桌面环境 (4)
linux·学习·ubuntu
Lueeee.1 小时前
图解字符驱动模块设计思路
linux
菜鸟233号1 小时前
力扣669 修剪二叉搜索树 java实现
java·数据结构·算法·leetcode
光羽隹衡2 小时前
机械学习逻辑回归——银行贷款案例
算法·机器学习·逻辑回归
白露与泡影2 小时前
使用systemd,把服务装进 Linux 心脏里~
linux·运维·python
CQ_YM2 小时前
Linux管道通信
linux·c语言·管道·ipc·管道通信