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;
    }
}
相关推荐
qq_452396233 分钟前
第三篇:Transactional Outbox 模式详解
java·kubernetes·rocketmq
3095566661 小时前
股票接口重试怎么分类:正常、空数组与错误响应的幂等处理
java·大数据·开发语言·数据库·php·api接口·股票数据api接口
摇滚侠7 小时前
《On Java 中文版 基础卷》阅读笔记 内部类 21
java·开发语言·笔记
凌冰_9 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
Rain的Java大神之路10 小时前
Spring AI 2.0 GA 深度复盘:Java 后端做 AI 的分水岭,到底画在哪?
java·后端·aigc
如夏倾城12 小时前
进程状态模型详解:从三态、五态到 Linux 状态码映射
java·linux·服务器
小南家的青蛙13 小时前
JVM 参数调优实战指南
java·jvm
SimonKing14 小时前
Typora 收费,开源产品Textus或可替代,还支持AI
java·后端·程序员
泡海椒14 小时前
Java 生成资金流向图 PDF:jquick-pdf 树图(JTreeChartData)节点尺寸与间距的追问记录
java·python·pdf