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;
    }
}
相关推荐
烟花落o3 分钟前
【数据结构系列04】随机链表的复制、环形链表I、环形链表||
数据结构·算法·leetcode·链表
senijusene4 分钟前
Linux软件编程: 线程属性与线程间通信详解
java·linux·jvm·算法
昱宸星光6 分钟前
spring cloud gateway内置路由断言工厂
java·开发语言·前端
亓才孓8 分钟前
jdk动态代理和Cglib动态代理的区别,为什么Cglib更适配SpringAOP
java·开发语言
塔中妖10 分钟前
Windows 安装 Maven 详细教程(含镜像与本地仓库配置)
java·windows·maven
colicode1 小时前
安卓Android语音验证码接口API示例代码:Kotlin/Java版App验证开发
android·java·前端·前端框架·kotlin·语音识别
Java后端的Ai之路1 小时前
【 Java】-网络协议核心知识问答(比较全)
java·开发语言·网络协议
小道仙978 小时前
jenkins对接、jenkins-rest
java·servlet·jenkins·jenkins-rest
pursuit_csdn9 小时前
LeetCode 1022. Sum of Root To Leaf Binary Numbers
算法·leetcode·深度优先
莫寒清9 小时前
MinIO
java