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;
    }
}
相关推荐
毕设源码-邱学长2 小时前
【开题答辩全过程】以 基于Java的学校住宿管理系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
I_LPL4 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
兑生4 小时前
【灵神题单·贪心】1481. 不同整数的最少数目 | 频率排序贪心 | Java
java·开发语言
daidaidaiyu4 小时前
一文学习 Spring 声明式事务源码全流程总结
java·spring
零雲5 小时前
java面试:了解抽象类与接口么?讲一讲它们的区别
java·开发语言·面试
左左右右左右摇晃8 小时前
Java并发——synchronized锁
java·开发语言
灰色小旋风9 小时前
力扣13 罗马数字转整数
数据结构·c++·算法·leetcode
sxlishaobin9 小时前
Java I/O 模型详解:BIO、NIO、AIO
java·开发语言·nio
彭于晏Yan9 小时前
Spring AI(二):入门使用
java·spring boot·spring·ai
有一个好名字9 小时前
vibe codeing 开发流程
java