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;
    }
}
相关推荐
无巧不成书021820 小时前
30分钟入门Java:从历史到Hello World的小白指南
java·开发语言
Tisfy1 天前
LeetCode 2839.判断通过操作能否让字符串相等 I:if-else(两两判断)
算法·leetcode·字符串·题解
zs宝来了1 天前
Playwright 自动发布 CSDN 的完整实践
java
吴声子夜歌1 天前
TypeScript——基础类型(三)
java·linux·typescript
DynamicsAgg1 天前
企业数字化底座-k8s企业实践系列第二篇pod创建调度
java·容器·kubernetes
森林里的程序猿猿1 天前
并发设计模式
java·开发语言·jvm
222you1 天前
四个主要的函数式接口
java·开发语言
Javatutouhouduan1 天前
Java全栈面试进阶宝典:内容全面,题目高频!
java·高并发·java面试·java面试题·后端开发·java程序员·java八股文
SEO-狼术1 天前
RAD Studio 13.1 Florence adds
java