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;
    }
}
相关推荐
songcream114 小时前
Spring Boot资料整理
java·spring boot·后端
源码宝15 小时前
新一代医院信息系统云HIS,多租户共享,java版HIS+EMR+LIS全套源码
java·大数据·源码·云his·his系统·源代码·医院信息系统
iiiiyu15 小时前
面向对象高级接口的综合案例
java·开发语言·数据结构·编程语言
fzil00115 小时前
让 AI 自己协作 —— 多智能体(Swarm)系统的设计与实现
java·开发语言·人工智能·ubuntu
Mem0rin15 小时前
[Java/数据结构]二叉树练习题几则
java·开发语言·数据结构
圣保罗的大教堂15 小时前
leetcode 2069. 模拟行走机器人 II 中等
leetcode
lhbian15 小时前
PHP vs Java vs Go:编程语言终极对比
java·spring boot·后端·kafka·linq
java修仙传15 小时前
从手写 Redis 锁到 Redisson:我对分布式锁安全性的理解
java·数据库·redis·分布式
iiiiyu15 小时前
常用API(Object类 & Objects类)
java·开发语言
小碗羊肉15 小时前
【从零开始学Java | 第三十六篇】字符流
java·开发语言