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;
    }
}
相关推荐
zhanghaofaowhrql13 分钟前
Spring Data JPA Repository 详解:从基础到高级用法
java·数据库·sql
编程(变成)小辣鸡1 小时前
如何防止接口被恶意刷?
java·后端·网络安全
大圣编程6 小时前
Java 多维数组详解
java·开发语言
Sw1zzle8 小时前
算法入门(四):二叉树 - 递归遍历三件套
算法·leetcode
万法若空8 小时前
【算法-查找】查找算法
java·数据结构·算法
海石9 小时前
子树怎么找?树的3种遍历方式来帮忙!
算法·leetcode
海石9 小时前
难度分 1588:思路 + 技巧 = AC
算法·leetcode
HZZD_HZZD11 小时前
DL/T 645-2026新国标深度解读与智能电表协议适配实战:从帧结构变化到Java采集器升级的全链路改造方案
java·开发语言
山登绝顶我为峰 3(^v^)313 小时前
C/C++ 交叉编译方法
java·c语言·c++