【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;
    }  
    }
相关推荐
挽天java5 小时前
数据结构习题--寻找旋转排序数组中的最小值
数据结构·算法·排序算法
郝亚军5 小时前
如何在windows11和Ubuntu linux之间互传文件
linux·运维·ubuntu
ghostmen5 小时前
Kuboard 离线安装与 K3s 集群绑定完整指南
linux·kuboard·k3s
j_xxx404_6 小时前
Linux:进程状态
linux·运维·服务器
济6176 小时前
linux 系统移植(第二十三期)---- 进一步完善BusyBox构建的根文件系统---- Ubuntu20.04
linux·运维·服务器
你怎么知道我是队长6 小时前
C语言---排序算法4---希尔排序法
c语言·算法·排序算法
程序员 _孜然6 小时前
openkylin、ubuntu等系统实现串口自动登录
linux·运维·ubuntu
iAkuya6 小时前
(leetcode)力扣100 54实现Trie树
算法·leetcode·c#
hweiyu006 小时前
Linux 命令:csplit
linux·运维·服务器
守正出琦6 小时前
Linux信号核心函数速查表
linux·运维·服务器