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;
    }
}
相关推荐
JIngJaneIL6 分钟前
智慧物业|物业管理|基于SprinBoot+vue的智慧物业管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·论文·智慧物业管理系统
ANYOLY18 分钟前
Redis 面试题库
java·redis·面试
懒惰蜗牛25 分钟前
Day63 | Java IO之NIO三件套--选择器(下)
java·nio·选择器·selector·半包粘包·tcp缓冲区
JavaGuide32 分钟前
美团2026届后端一二面(附详细参考答案)
java·后端
打工人你好34 分钟前
如何设计更安全的 VIP 权限体系
java·jvm·安全
L.EscaRC41 分钟前
Spring IOC核心原理与运用
java·spring·ioc
摇滚侠1 小时前
2025最新 SpringCloud 教程,Nacos-总结,笔记19
java·笔记·spring cloud
在逃热干面1 小时前
(笔记)获取终端输出保存到文件
java·笔记·spring
爱笑的眼睛111 小时前
深入理解MongoDB PyMongo API:从基础到高级实战
java·人工智能·python·ai
leoufung1 小时前
逆波兰表达式 LeetCode 题解及相关思路笔记
linux·笔记·leetcode