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;
    }
}
相关推荐
一水23 分钟前
TTFT优化:一个方案的5次推倒重来
java·ai·状态模式
AC赳赳老秦29 分钟前
CSDN 技术社区数据采集:OpenClaw 抓取公开技术热帖,生成领域技术热点周报
java·大数据·前端·数据库·python·php·openclaw
磁爆步兵1 小时前
内存分区:程序运行的核心秘密
java·开发语言·jvm
流星白龙2 小时前
【Docker】4.NameSpace空间隔离实战
java·运维·docker
AI人工智能+电脑小能手2 小时前
【大白话说Java面试题 第207题】【09_Zookeeper篇】第8题:谈谈 ZooKeeper 的可靠性保障机制
java·zookeeper·高可用·可靠性·分布式系统
harmful_sheep2 小时前
maven多版本包导致java.lang.NoClassDefFoundError
java·maven
Mark_ZP2 小时前
【锁2】锁的分类与概念
java·
caishenzhibiao2 小时前
顺势捕猎者副图 同花顺期货通指标
java·c语言·c#
Hi李耶3 小时前
【LeetCode】9-回文数
算法·leetcode·职场和发展
笨蛋不要掉眼泪3 小时前
RabbitMQ消息队列:SpringAMQP
java·分布式·rabbitmq