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;
    }
}
相关推荐
5系暗夜孤魂2 分钟前
系统越复杂,越需要“边界感”:从 Java 体系理解大型工程的可维护性本质
java·开发语言
二月夜16 分钟前
Spring循环依赖深度解析:从三级缓存原理到跨环境“灵异”现象
java·spring
nbwenren1 小时前
Springboot中SLF4J详解
java·spring boot·后端
wellc1 小时前
java进阶知识点
java·开发语言
灰色小旋风1 小时前
力扣合并K个升序链表C++
java·开发语言
_MyFavorite_1 小时前
JAVA重点基础、进阶知识及易错点总结(28)接口默认方法与静态方法
java·开发语言·windows
Kk.08021 小时前
力扣 LCR 084.全排列||
算法·leetcode·职场和发展
旖-旎2 小时前
分治(快速选择算法)(3)
c++·算法·leetcode·排序算法·快速选择
helx822 小时前
SpringBoot中自定义Starter
java·spring boot·后端
_MyFavorite_2 小时前
JAVA重点基础、进阶知识及易错点总结(31)设计模式基础(单例、工厂)
java·开发语言·设计模式