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;
    }
}
相关推荐
Lyyaoo.15 小时前
【JAVA基础面经】进程间的通信方式
java·开发语言·python
We་ct15 小时前
LeetCode 149. 直线上最多的点数:题解深度剖析
前端·javascript·算法·leetcode·typescript
sheeta199815 小时前
LeetCode 每日一题笔记 日期:2026.04.13 题目:1848.到目标元素的最小距离
笔记·算法·leetcode
小坏讲微服务15 小时前
Claude Code 终极实战指南:从终端 Agent 到 AI+Java 开发
java·开发语言·人工智能
Tisfy15 小时前
LeetCode 1848.到目标元素的最小距离:数组遍历(附python一行版)
python·leetcode·题解·遍历
ch.ju15 小时前
Java程序设计(第3版)第二章——类型转换(2)
java
斌味代码15 小时前
NestJS 高并发实战:从异步到集群的完整方案
java·spring boot·spring
jarvisuni15 小时前
JCode添加批量测试,一键同步运行6个Claude Code!
java·服务器·前端
组合缺一15 小时前
Snack JSONPath 项目架构分析
java·架构·json·jsonpath·rfc 9535
人道领域15 小时前
2026年Java后端热点科普:Java 26新特性+Java 21落地实战,解锁后端开发新范式
java·开发语言