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;
    }
}
相关推荐
圣保罗的大教堂3 小时前
leetcode 3418. 机器人可以获得的最大金币数 中等
leetcode
WiChP3 小时前
【V0.1B5】从零开始的2D游戏引擎开发之路
java·服务器·数据库
cch89183 小时前
汇编与Java:底层与高层的编程对决
java·开发语言·汇编
荒川之神4 小时前
拉链表概念与基本设计
java·开发语言·数据库
cch89184 小时前
汇编与Go:底层到高层的编程差异
java·汇编·golang
chushiyunen4 小时前
python中的@Property和@Setter
java·开发语言·python
禾小西4 小时前
Java中使用正则表达式核心解析
java·python·正则表达式
yoyo_zzm4 小时前
JAVA (Springboot) i18n国际化语言配置
java·spring boot·python
APIshop4 小时前
Java获取京东商品详情接口(item_get)实战指南
java·linux·数据库