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;
    }
}
相关推荐
星落梦生17 分钟前
SpringAOP基础笔记(7)
java·开发语言
金銀銅鐵1 小时前
带您看懂字节码指令(四):一条指令里有什么
java·jvm
最强小杰2 小时前
某 OpenAI 兼容网关上的 `kimi-k3.1-pro`:Cline、Zed 接入与 SSE 排错示例
java·服务器·网络·ai
Flynn Liang2 小时前
流量治理不是限流那么简单:I/O 密集型 Java 服务的 6 层防线
java·微服务·高并发·限流·熔断·系统稳定性·resilience4j
学长毕设2 小时前
基于SpringBoot智慧养老服务平台设计与实现-附源码
java·spring boot·后端
曹牧3 小时前
Java:“刷新雪崩”
java·开发语言
秋天的怀念_David3 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
Forget the Dream4 小时前
Spring AI 2.0 系列(二):第一个 ChatClient——从注入到一次完整调用
java·人工智能·spring boot·ai·springai
LK_075 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi6 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展