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 分钟前
编程语言编译运行机制对比:C / Java / Python
java·c语言·python
慧一居士4 分钟前
对比两个文件内容是否完全一致,java实现示例
java
再写一行代码就下班19 分钟前
Cursor配置Java环境、创建Spring Boot项目的步骤
java·开发语言·spring boot
摇滚侠23 分钟前
Java 零基础全套教程,类的加载过程与类加载器的理解,笔记 189
java·后端·intellij-idea
小欣加油30 分钟前
leetcode287寻找重复数
数据结构·c++·算法·leetcode
kong@react44 分钟前
Rocky Linux 10.2 全面解析:企业级 CentOS 替代方案及保姆级docker安装
java·linux·运维·docker
未若君雅裁1 小时前
JVM 运行时数据区:程序计数器、堆、虚拟机栈与栈帧
java·jvm
凡人叶枫1 小时前
Effective C++ 条款10:令 operator= 返回一个 reference to *this
java·linux·服务器·开发语言·c++·effective c++
摇滚侠1 小时前
JavaSE 和 JavaEE 是什么意思
java·java-ee
想带你从多云到转晴1 小时前
03、JAVAEE---多线程(三)
java