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;
    }
}
相关推荐
TracyCoder1237 小时前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
开发者小天7 小时前
python中For Loop的用法
java·服务器·python
flushmeteor7 小时前
JDK源码-基础类-String
java·开发语言
毕设源码-钟学长7 小时前
【开题答辩全过程】以 基于ssm的空中停车场管理系统为例,包含答辩的问题和答案
java
不愿是过客8 小时前
java实战干货——长方法深递归
java
小北方城市网9 小时前
Redis 分布式锁高可用实现:从原理到生产级落地
java·前端·javascript·spring boot·redis·分布式·wpf
六义义9 小时前
java基础十二
java·数据结构·算法
毕设源码-钟学长10 小时前
【开题答辩全过程】以 基于SpringBoot的智能书城推荐系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
weixin_4454766810 小时前
leetCode每日一题——边反转的最小成本
算法·leetcode·职场和发展
笨手笨脚の10 小时前
深入理解 Java 虚拟机-03 垃圾收集
java·jvm·垃圾回收·标记清除·标记复制·标记整理