Java | Leetcode Java题解之第429题N叉树的层序遍历

题目:

题解:

java 复制代码
class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        if (root == null) {
            return new ArrayList<List<Integer>>();
        }

        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        Queue<Node> queue = new ArrayDeque<Node>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int cnt = queue.size();
            List<Integer> level = new ArrayList<Integer>();
            for (int i = 0; i < cnt; ++i) {
                Node cur = queue.poll();
                level.add(cur.val);
                for (Node child : cur.children) {
                    queue.offer(child);
                }
            }
            ans.add(level);
        }

        return ans;
    }
}
相关推荐
砍材农夫2 小时前
spring-ai 第四多模态API
java·人工智能·spring
她说..4 小时前
Java 对象相关高频面试题
java·开发语言·spring·java-ee
Boop_wu5 小时前
[Java 算法] 字符串
linux·运维·服务器·数据结构·算法·leetcode
庞轩px5 小时前
深入理解 sleep() 与 wait():从基础到监视器队列
java·开发语言·线程··wait·sleep·监视器
皮皮林5516 小时前
面试官:ZSet 的底层实现是什么?
java
码云数智-大飞6 小时前
C++ RAII机制:资源管理的“自动化”哲学
java·服务器·php
2601_949816586 小时前
Spring+Quartz实现定时任务的配置方法
java
计算机毕设指导67 小时前
基于SpringBoot校园学生健康监测管理系统【源码文末联系】
java·spring boot·后端·spring·tomcat·maven·intellij-idea
mysuking7 小时前
springboot与springcloud对应版本
java·spring boot·spring cloud
希望永不加班7 小时前
SpringBoot 数据库连接池配置(HikariCP)最佳实践
java·数据库·spring boot·后端·spring