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;
    }
}
相关推荐
BeyondESH9 分钟前
C++—单例设计模式
java·c++·设计模式
好奇的菜鸟16 分钟前
探索 JUnit 5:下一代 Java 测试框架
java·开发语言·junit
爱吃土豆的程序员16 分钟前
Lucene 倒排索引原理详解:深入探讨相关算法设计
java·算法·elasticsearch·全文检索·lucene
林小果116 分钟前
桥接模式
java·开发语言·设计模式
MicrosoftReactor1 小时前
技术速递|宣布 Azure Container Apps 上的 Java 体验正式推出
java·azure
顾城猿1 小时前
9.25-编程刷题
数据结构·算法·leetcode
情书2 小时前
Java调用第三方接口、http请求详解,一文学会
java·开发语言·http
Chrikk2 小时前
LeetCode146 LRU缓存
java·c++·spring·缓存
好看资源平台2 小时前
Spring 全家桶使用教程 —— 后端开发从入门到精通
java·数据库·spring
Satan7122 小时前
【Spring】Spring Aop基础入门
java·开发语言·jvm