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;
    }
}
相关推荐
Elias不吃糖5 小时前
Java Lambda 表达式
java·开发语言·学习
夏鹏今天学习了吗5 小时前
【LeetCode热题100(83/100)】最长递增子序列
算法·leetcode·职场和发展
情缘晓梦.5 小时前
C语言指针进阶
java·开发语言·算法
AlenTech7 小时前
155. 最小栈 - 力扣(LeetCode)
算法·leetcode·职场和发展
南知意-7 小时前
IDEA 2025.3 版本安装指南(完整图文教程)
java·intellij-idea·开发工具·idea安装
码农水水7 小时前
蚂蚁Java面试被问:混沌工程在分布式系统中的应用
java·linux·开发语言·面试·职场和发展·php
海边的Kurisu7 小时前
苍穹外卖日记 | Day4 套餐模块
java·苍穹外卖
毕设源码-邱学长8 小时前
【开题答辩全过程】以 走失儿童寻找平台为例,包含答辩的问题和答案
java
坚持不懈的大白8 小时前
Leetcode学习笔记
笔记·学习·leetcode
他们叫我技术总监8 小时前
Python 列表、集合、字典核心区别
android·java·python