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;
    }
}
相关推荐
爱喝可乐的中登4 分钟前
SpringBoot 云边协同|智慧地铁 ISCS 改造实战第 10 篇:全网权限与数据隔离重构|线路‑车站‑专业三级 RBAC、边缘数据权限下沉
java·spring boot·重构
落魄实习生17 分钟前
Spring AI Alibaba入门-生态集成
java·人工智能·spring
重生之我是Java开发战士24 分钟前
【Java EE】认识Linux与项目部署
java·linux·java-ee
LXMXHJ27 分钟前
springboot项目测试
java·spring boot·后端·测试
程序员雪球35 分钟前
本地IDEA打断点debug容器
java·开发语言
码匠许师傅44 分钟前
【设计模式精讲】2. 设计原则基石:SOLID 与几条关键原则
java·设计模式·log4j
Tisfy1 小时前
LeetCode 3720.大于目标字符串的最小字典序排列:状态机 —— :从左往右枚举,失败则退回(最多退回一次)
linux·数据库·leetcode·字符串·状态机·构造
yychen_java1 小时前
二:Multi-Agent 协作架构与 MCP 协议实战:Java 企业级 AI 智能体进阶指南
java·人工智能·架构
老白干1 小时前
基于枚举 + 注解的 Java 数据脱敏实践(fastjson 序列化场景)
java·开发语言
SKH.1 小时前
Linux软件编程(5)线程
java·linux·jvm