【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;
    }  
    }
相关推荐
网硕互联的小客服3 小时前
Linux服务器磁盘应该如何合理分区?
linux·运维·服务器
不会就选b3 小时前
算法日常・每日刷题--<贪心>25
数据结构·算法
贵沫末4 小时前
Ubuntu——常用软件安装
linux·运维·ubuntu
Doraemomo4 小时前
Linux内核驱动开发——中断与定时器
linux·运维·驱动开发
2301_808414385 小时前
Linux中动静态库的理解
linux·运维·服务器
M78佐菲6 小时前
ARM学习笔记(11)
linux·arm开发·笔记·嵌入式硬件·学习
M78佐菲6 小时前
ARM学习笔记(10)
linux·arm开发·笔记·嵌入式硬件·学习
半仙白桑6 小时前
内核篇第十五讲:system-V共享内存
linux·共享内存·shmget·shmat·shmdt·shmctl
一条破秋裤6 小时前
Linux 线程创建:pthread_create 与基本回收
java·linux·运维
Cccp.1236 小时前
【leetcode】(七)前缀树和贪心算法
数据结构·leetcode·贪心算法