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;
    }
}
相关推荐
格鸰爱童话6 分钟前
向AI学习项目技能(三)
java·人工智能·python·学习
weixin1997010801611 分钟前
南网商城商品详情页前端性能优化实战
java·前端·性能优化
Sakinol#12 分钟前
Leetcode Hot 100 —— 矩阵
leetcode·矩阵
iPadiPhone14 分钟前
Spring Boot 自动装配原理与 Starter 开发实战
java·spring boot·后端·spring·面试
SuGarSJL15 分钟前
FakeSMTP-2.1.1使用
java·maven
码匠君16 分钟前
首个基于 Spring Boot 4 的正式版发布!Dante Cloud 4.X 新特性全解析
java·spring boot·后端
悟空码字26 分钟前
SpringBoot + 百度地图SDK,打造企业级位置服务中台
java·百度·地图·编程技术·后端开发
weixin1997010801628 分钟前
网易考拉商品详情页前端性能优化实战
java·前端·python·性能优化
Natalia_Portman29 分钟前
springboot整合DolphinDB
java·数据库·spring boot·后端·db