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;
    }
}
相关推荐
咸鱼2.02 小时前
【java入门到放弃】跨域
java·开发语言
indexsunny2 小时前
互联网大厂Java求职面试实战:微服务与Spring生态全攻略
java·数据库·spring boot·安全·微服务·面试·消息队列
沐苏瑶2 小时前
Java 搜索型数据结构全解:二叉搜索树、Map/Set 体系与哈希表
java·数据结构·算法
冬夜戏雪3 小时前
实习面经记录(十)
java·前端·javascript
skiy3 小时前
java与mysql连接 使用mysql-connector-java连接msql
java·开发语言·mysql
平生不喜凡桃李3 小时前
浅谈 Linux 中 namespace 相关系统调用
java·linux·服务器
zb200641203 小时前
CVE-2024-38819:Spring 框架路径遍历 PoC 漏洞复现
java·后端·spring
2401_895521343 小时前
spring-ai 下载不了依赖spring-ai-openai-spring-boot-starter
java·人工智能·spring
_日拱一卒4 小时前
LeetCode:找到字符串中的所有字母异位词
算法·leetcode
何仙鸟4 小时前
GarmageSet下载和处理
java·开发语言