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;
    }
}
相关推荐
周杰偷奶茶9 分钟前
【Java】数组的定义和使用(附管理系统实战案例)
java·开发语言
橙子圆1231 小时前
JUC之集合类不安全
java·开发语言
谢亮_vipxieliang2 小时前
Stream API 不是银弹:常见坑与性能建议
java·开发语言
源码宝2 小时前
Web‑PACS 云影像源码|Java+Vue3 医院影像管理系统完整方案
java·源码·影像pacs·成品源码·医院影像系统
ShineWinsu2 小时前
对于Redis:string类型的解析
java·c++·redis·分布式·缓存·面试·string
三8444 小时前
Fastjson 漏洞 · 02 · autoType 机制与 checkAutoType
java·fastjson
想吃火锅10054 小时前
【leetcode】238.除了自身以外数组的乘积js
javascript·算法·leetcode
无限码力4 小时前
小红书笔试真题 9.17 - 待发热度重排(C++/Py/Java /Js/Go)
java·小红书·小红书笔试真题·小红书技术岗笔试真题
卓怡学长5 小时前
w194基于ssm新能源汽车充电系统小程序
java·小程序·intellij-idea