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;
    }
}
相关推荐
星晨雪海13 分钟前
企业标准 DTO 传参 + Controller + Service + 拷贝工具类完整版
java·开发语言·python
pshdhx_albert7 小时前
AI agent实现打字机效果
java·http·ai编程
沉鱼.448 小时前
第十二届题目
java·前端·算法
赫瑞9 小时前
数据结构中的排列组合 —— Java实现
java·开发语言·数据结构
周末也要写八哥10 小时前
多进程和多线程的特点和区别
java·开发语言·jvm
惜茶11 小时前
vue+SpringBoot(前后端交互)
java·vue.js·spring boot
杰克尼11 小时前
springCloud_day07(MQ高级)
java·spring·spring cloud
NHuan^_^13 小时前
SpringBoot3 整合 SpringAI 实现ai助手(记忆)
java·人工智能·spring boot
Mr_Xuhhh13 小时前
从ArrayList到LinkedList:理解链表,掌握Java集合的另一种选择
java·数据结构·链表
倦王13 小时前
力扣日刷47-补
python·算法·leetcode