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;
    }
}
相关推荐
enjoy嚣士5 分钟前
springboot之Exel工具类
java·spring boot·后端·easyexcel·excel工具类
罗超驿17 分钟前
独立实现双向链表_LinkedList
java·数据结构·链表·linkedlist
盐水冰1 小时前
【烘焙坊项目】后端搭建(12) - 订单状态定时处理,来单提醒和顾客催单
java·后端·学习
凸头1 小时前
CompletableFuture 与 Future 对比与实战示例
java·开发语言
wuqingshun3141591 小时前
线程安全需要保证几个基本特征
java·开发语言·jvm
努力也学不会java2 小时前
【缓存算法】一篇文章带你彻底搞懂面试高频题LRU/LFU
java·数据结构·人工智能·算法·缓存·面试
攒了一袋星辰2 小时前
高并发强一致性顺序号生成系统 -- SequenceGenerator
java·数据库·mysql
小涛不学习2 小时前
Spring Boot 详解(从入门到原理)
java·spring boot·后端
于先生吖3 小时前
Java框架开发短剧漫剧系统:后台管理与接口开发
java·开发语言
daidaidaiyu3 小时前
Spring IOC 源码学习 声明式事务的入口点
java·spring