【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 分钟前
DNS服务(Linux)
linux·运维·服务器
Fantasydg5 分钟前
DAY 39 leetcode 18--哈希表.四数之和
算法·leetcode·散列表
程序猿John23 分钟前
Linux下创建svn库 和 svn安装与操作
linux·运维·svn
kfepiza31 分钟前
btrfs , ext4 , jfs , ntfs , refs , xfs , zfs 对比笔记250406
linux·windows·笔记
半新半旧44 分钟前
keepalived高可用介绍
linux·服务器·网络
WG_171 小时前
图论:最小生成树
算法·图论
写个博客1 小时前
代码随想录算法训练营第十一天
算法
Protein_zmm1 小时前
[数据结构]图krusakl算法实现
数据结构·算法
旧厂街小江1 小时前
LeetCode 第111题:二叉树的最小深度
前端·算法·程序员
ci0n2 小时前
PVE安装DSM
linux·开源