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 小时前
LeetCode 移动零元素 快慢指针
算法·leetcode·职场和发展
28岁青春痘老男孩2 小时前
JDK8+SpringBoot2.x 升级 JDK 17 + Spring Boot 3.x
java·spring boot
方璧2 小时前
限流的算法
java·开发语言
元Y亨H3 小时前
Nacos - 服务注册
java·微服务
曲莫终3 小时前
Java VarHandle全面详解:从入门到精通
java·开发语言
一心赚狗粮的宇叔3 小时前
中级软件开发工程师2025年度总结
java·大数据·oracle·c#
奋进的芋圆3 小时前
DataSyncManager 详解与 Spring Boot 迁移指南
java·spring boot·后端
计算机程序设计小李同学4 小时前
个人数据管理系统
java·vue.js·spring boot·后端·web安全
漫随流水4 小时前
leetcode算法(515.在每个树行中找最大值)
数据结构·算法·leetcode·二叉树
小途软件4 小时前
用于机器人电池电量预测的Sarsa强化学习混合集成方法
java·人工智能·pytorch·python·深度学习·语言模型