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;
    }
}
相关推荐
带刺的坐椅5 小时前
Solon AI Skills 会是 Agent 的未来吗?
java·agent·langchain4j·solon-ai
夏鹏今天学习了吗5 小时前
【LeetCode热题100(87/100)】最小路径和
算法·leetcode·职场和发展
jacGJ5 小时前
记录学习--文件读写
java·前端·学习
花间相见6 小时前
【JAVA开发】—— Nginx服务器
java·开发语言·nginx
扶苏-su6 小时前
Java---Properties 类
java·开发语言
cypking6 小时前
四、CRUD操作指南
java
2301_780669867 小时前
文件字节流输出、文件复制、关闭流的方法
java
Lips6118 小时前
2026.1.20力扣刷题笔记
笔记·算法·leetcode
剑锋所指,所向披靡!8 小时前
C++之类模版
java·jvm·c++
Coder_Boy_8 小时前
基于SpringAI的在线考试系统-0到1全流程研发:DDD、TDD与CICD协同实践
java·人工智能·spring boot·架构·ddd·tdd