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;
    }
}
相关推荐
柚个朵朵12 分钟前
Spring的Validation,这是一套基于注解的权限校验框架
java·后端·spring
2301_8035545215 分钟前
c++和c的不同
java·c语言·c++
意倾城1 小时前
JVM内存模型
java·jvm
普通的冒险者1 小时前
几个简单的数组小练习(适合初学)
java·数据结构
keke101 小时前
Java【10_1】用户注册登录(面向过程与面向对象)
java·python·intellij-idea
程序员buddha1 小时前
Spring & Spring Boot 常用注解整理
java·spring boot·spring
C_V_Better1 小时前
Java Spring Boot 控制器中处理用户数据详解
java·开发语言·spring boot·后端·spring
胡子洲1 小时前
Spring Boot 应用中实现基本的 SSE 功能
java·spring boot·后端
t198751281 小时前
基于Qt的OSG三维建模
java·开发语言
SoFlu软件机器人2 小时前
Java 框架配置自动化:告别冗长的 XML 与 YAML 文件
xml·java·自动化