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;
    }
}
相关推荐
fengci.3 分钟前
ctfshow(web入门)279-286
java·开发语言·学习
fy121634 分钟前
navicat15安装破解
java
ok_hahaha9 分钟前
java从头开始-苍穹外卖day05-Redis及店铺营业状态设置
java·开发语言·redis
加洛斯33 分钟前
JAVA知识梳理:一文搞懂集合中的List与ArrayList的基础与进阶
java·后端·面试
架构师沉默1 小时前
女孩去旅行,给男朋友带回了一个难解的 Bug
java·后端·架构
xu_ws1 小时前
Spring-ai项目-deepseek-6-哄哄模拟器
java·人工智能·spring
刘 大 望1 小时前
SpringAI Tool Calling(工具调用)
java·spring boot·spring·ai·maven·intellij-idea·文心一言
222you1 小时前
Java 并发编程(1)
java·开发语言
样例过了就是过了1 小时前
LeetCode热题100 分割回文串
数据结构·c++·算法·leetcode·深度优先·dfs
岁岁种桃花儿1 小时前
kubenetes从入门到上天系列第十九篇:Kubernetes安装Nginx ingress controller
java·nginx·kubernetes