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;
    }
}
相关推荐
夏乌_Wx21 分钟前
练题100天——DAY23:存在重复元素Ⅰ Ⅱ+两数之和
数据结构·算法·leetcode
小小8程序员38 分钟前
STL 库(C++ Standard Template Library)全面介绍
java·开发语言·c++
a努力。1 小时前
Redis Java 开发系列#2 数据结构
java·数据结构·redis
a努力。2 小时前
腾讯Java面试被问:String、StringBuffer、StringBuilder区别
java·开发语言·后端·面试·职场和发展·架构
Vic101013 小时前
解决 Spring Security 在异步线程中用户信息丢失的问题
java·前端·spring
QD_IT伟3 小时前
SpringBoot项目整合Tlog 数据链路的规范加强
java·spring boot·后端
源码获取_wx:Fegn08953 小时前
基于springboot + vue二手交易管理系统
java·vue.js·spring boot·后端·spring·课程设计
Zsh-cs3 小时前
Spring
java·数据库·spring
爬山算法3 小时前
Springboot请求和响应相关注解及使用场景
java·spring boot·后端
程序员水自流3 小时前
MySQL InnoDB存储引擎详细介绍之事务
java·数据库·mysql·oracle