【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;
    }  
    }
相关推荐
kebidaixu30 分钟前
两轮BMS 短路保护策略详解
算法
qq_1631357534 分钟前
Linux 【03- chgrp命令超详细教程】
linux
zwenqiyu1 小时前
非线性字符串数据结构串讲
数据结构·c++·学习·算法
z小猫不吃鱼1 小时前
03 Optimal Brain Surgeon 详解:Hessian 剪枝为什么有效?
算法·机器学习·剪枝
硕风和炜1 小时前
【LeetCode: 1301. 最大得分的路径数目 + DP】
java·算法·leetcode·动态规划·dp·记忆化搜索
用户99045017780091 小时前
做了一个AI诊断,参考倪海厦中医理论,科学养生
算法
我会尽全力 乐观而坚强2 小时前
MySQL库与表的操作
linux·数据库·mysql
努力中的编程者2 小时前
STL-vector的模拟实现
开发语言·c++·算法·stl·vector
着迷不白2 小时前
Linux 磁盘管理完全指南:分区、文件系统、挂载与 LVM 实战
linux·运维·服务器
山川而川-R2 小时前
LangChain
linux·运维·服务器