【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;
    }  
    }
相关推荐
tianyuanwo10 小时前
DevOps主机管理员视角:企业级Linux主机权限管理策略与实践
linux·服务器·devops
郭涤生10 小时前
Windows + Ubuntu 双系统启动故障修复
linux·windows·ubuntu
三言老师10 小时前
CentOS8 Firewalld 高级规则中级实操教程
linux·运维·服务器·网络·centos
Forever Nore11 小时前
LeetCode 1 两数之和
算法·leetcode·职场和发展
To_OC11 小时前
LC 3 无重复字符的最长子串:从入门滑动窗口到优化写法,再也不怕面试官追问
javascript·算法·leetcode
(Charon)12 小时前
【C++】多线程死锁:产生原因、复现与解决方法
开发语言·c++·算法
tedcloud12312 小时前
Impeccable 部署指南:开源前端设计工具 Linux 环境搭建实践
linux·运维·服务器·前端·人工智能·开源
风曦Kisaki12 小时前
# Kubernetes(K8s)笔记Day12 :K8s 七层代理(Ingress 和 Ingress Controller)
linux·笔记·云原生·容器·kubernetes
大黄说说12 小时前
SQL Server 执行计划怎么看?快速定位 SQL 慢的根源
java·linux·数据库
lucas_AI12 小时前
ConfBench:大模型的「我很有把握」,到底能不能信?
人工智能·算法