【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;
    }  
    }
相关推荐
_日拱一卒12 分钟前
LeetCode:240搜索二维矩阵Ⅱ
数据结构·线性代数·leetcode·矩阵
WolfGang00732113 分钟前
代码随想录算法训练营 Day33 | 动态规划 part06
算法·leetcode·动态规划
aini_lovee13 分钟前
半定规划(SDP)求解的 MATLAB 实现
算法
爱学习的小囧21 分钟前
嵌套式 ESXi 8.x/9.0 虚拟设备下载与实战指南
java·linux·运维·服务器·虚拟化
hj28625121 分钟前
初学linux命令day2
linux·运维·服务器
米粒124 分钟前
力扣算法刷题 Day 41(买卖股票)
算法·leetcode·职场和发展
幻风_huanfeng26 分钟前
人工智能之数学基础:内点法和外点法的区别和缺点
人工智能·算法·机器学习·内点法·外点法
硅基导游32 分钟前
linux系统与进程内存使用情况探测
java·linux·运维
MIngYaaa52035 分钟前
The 6th Liaoning Provincial Collegiate Programming Contest - External 复盘
算法
CylMK36 分钟前
题解:P11625 [迷宫寻路 Round 3] 迷宫寻路大赛
c++·数学·算法