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;
    }
}
相关推荐
flushmeteor21 分钟前
java的动态代理和字节码生成技术
java·动态代理·代理·字节码生成
eggwyw21 分钟前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring
0xDevNull26 分钟前
MySQL 别名(Alias)指南:从入门到避坑
java·数据库·sql
lv__pf30 分钟前
springboot原理
java·spring boot·后端
java1234_小锋31 分钟前
Java高频面试题:什么是可重入锁?
java·开发语言
云烟成雨TD1 小时前
Spring AI Alibaba 1.x 系列【22】Agent 并行工具执行与超时 / 协作式取消实战
java·人工智能·spring
段小二1 小时前
服务一重启全丢了——Spring AI Alibaba Agent 三层持久化完整方案
java·后端
段小二2 小时前
Agent 自动把机票改错了,推理完全正确——这才是真正的风险
java·后端
itjinyin2 小时前
ShardingSphere-jdbc 5.5.0 + spring boot 基础配置 - 实战篇
java·spring boot·后端
丶小鱼丶2 小时前
Java虚拟机【JVM】
java·jvm