【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;
    }  
    }
相关推荐
violet-lz25 分钟前
数据结构四大简单排序算法详解:直接插入排序、选择排序、基数排序和冒泡排序
数据结构·算法·排序算法
·白小白30 分钟前
力扣(LeetCode) ——118.杨辉三角(C++)
c++·算法·leetcode
tongsound34 分钟前
libmodbus 使用示例
linux·c++
拾光Ծ36 分钟前
【Linux】“ 权限 “ 与相关指令
linux·运维·服务器
硬核子牙40 分钟前
调试器是怎么让代码停下来的
linux
To_再飞行40 分钟前
Linux Bash(一)
linux·运维·服务器·bash
LCG元1 小时前
保姆级教程:CentOS 7/8 部署Nginx + MySQL + PHP(LEMP)环境,从零开始到上线项目
linux
CoovallyAIHub1 小时前
超越“识别”:下一代机器视觉如何破解具身智能落地难题?
深度学习·算法·计算机视觉
疯癫的老码农1 小时前
【Linux环境下安装】SpringBoot应用环境安装(五)-milvus安装
linux·spring boot·milvus
仰泳的熊猫1 小时前
LeetCode:207. 课程表
数据结构·c++·算法·leetcode