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;
    }
}
相关推荐
没有bug.的程序员17 小时前
服务网格 Service Mesh:微服务通信的终极进化
java·分布式·微服务·云原生·service_mesh
南尘NCA866620 小时前
企业微信防封防投诉拦截系统:从痛点解决到技术实现
java·网络·企业微信
怪兽201421 小时前
SQL优化手段有哪些
java·数据库·面试
ss27321 小时前
手写MyBatis第107弹:@MapperScan原理与SqlSessionTemplate线程安全机制
java·开发语言·后端·mybatis
Lris-KK21 小时前
力扣Hot100--94.二叉树的中序遍历、144.二叉树的前序遍历、145.二叉树的后序遍历
python·算法·leetcode
Deschen21 小时前
设计模式-原型模式
java·设计模式·原型模式
麦麦鸡腿堡21 小时前
Java的动态绑定机制(重要)
java·开发语言·算法
それども21 小时前
SpringBootTest运行线程池被拒绝
java
坚持编程的菜鸟1 天前
LeetCode每日一题——螺旋矩阵
c语言·算法·leetcode·矩阵