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;
    }
}
相关推荐
Vic1010128 分钟前
Java 开发笔记:多线程查询逻辑的抽象与优化
java·服务器·笔记
Biaobiaone29 分钟前
Java中的生产消费模型解析
java·开发语言
এ᭄画画的北北1 小时前
力扣-31.下一个排列
算法·leetcode
特立独行的猫a1 小时前
11款常用C++在线编译与运行平台推荐与对比
java·开发语言·c++
louisgeek1 小时前
Java 位运算
java
hweiyu002 小时前
Maven 私库
java·maven
Super Rookie2 小时前
Spring Boot 企业项目技术选型
java·spring boot·后端
写不出来就跑路2 小时前
Spring Security架构与实战全解析
java·spring·架构
ZeroNews内网穿透3 小时前
服装零售企业跨区域运营难题破解方案
java·大数据·运维·服务器·数据库·tcp/ip·零售
sleepcattt3 小时前
Spring中Bean的实例化(xml)
xml·java·spring