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;
    }
}
相关推荐
JWASX1 小时前
【RocketMQ 生产者和消费者】- 消费者重平衡(1)
java·rocketmq·重平衡
剽悍一小兔1 小时前
自动化文档生成工具(亲测可运行)
java
程序员皮皮林1 小时前
使用 Java + WebSocket 实现简单实时双人协同 pk 答题
java·websocket
栗然1 小时前
Spring Boot 项目中使用 MyBatis 的 @SelectProvider 注解并解决 SQL 注入的问题
java·后端
im_AMBER1 小时前
java复习 19
java·开发语言
陆少枫1 小时前
JDBC强化关键_009_连接池
java·数据库·mysql
安迪小宝1 小时前
2 geotools入门示例
java·spring boot
Moshow郑锴1 小时前
IDEA高效快捷键指南
java·ide·intellij-idea
小猫咪怎么会有坏心思呢2 小时前
华为OD机考-异常的打卡记录-字符串(JAVA 2025B卷)
java·开发语言·华为od
炎码工坊2 小时前
Java 时间处理指南:从“踩坑”到“填坑”实战
java·java-ee