【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;
    }  
    }
相关推荐
呆呆的小鳄鱼9 分钟前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香10 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely11 分钟前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_071211 分钟前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_27 分钟前
cf1925B&C
数据结构·算法
YuTaoShao1 小时前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先
退役小学生呀1 小时前
十五、K8s可观测能力:日志收集
linux·云原生·容器·kubernetes·k8s
van叶~1 小时前
Linux探秘坊-------15.线程概念与控制
linux·运维·服务器
Andy杨3 小时前
20250718-1-Kubernetes 应用程序生命周期管理-应用部署、升级、弹性_笔记
linux·docker·容器
写写闲篇儿6 小时前
Python+MongoDB高效开发组合
linux·python·mongodb