C++ | Leetcode C++题解之第429题N叉树的层序遍历

题目:

题解:

cpp 复制代码
class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        if (!root) {
            return {};
        }

        vector<vector<int>> ans;
        queue<Node*> q;
        q.push(root);

        while (!q.empty()) {
            int cnt = q.size();
            vector<int> level;
            for (int i = 0; i < cnt; ++i) {
                Node* cur = q.front();
                q.pop();
                level.push_back(cur->val);
                for (Node* child: cur->children) {
                    q.push(child);
                }
            }
            ans.push_back(move(level));
        }

        return ans;
    }
};
相关推荐
scx201310042 小时前
20250814 最小生成树和重构树总结
c++·算法·最小生成树·重构树
weixin_307779134 小时前
VS Code配置MinGW64编译SQLite3库
开发语言·数据库·c++·vscode·算法
无聊的小坏坏4 小时前
拓扑排序详解:从力扣 207 题看有向图环检测
算法·leetcode·图论·拓扑学
励志不掉头发的内向程序员5 小时前
STL库——string(类函数学习)
开发语言·c++
浮灯Foden7 小时前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
淡海水7 小时前
【原理】Struct 和 Class 辨析
开发语言·c++·c#·struct·class
执子手 吹散苍茫茫烟波9 小时前
leetcode415. 字符串相加
java·leetcode·字符串
青草地溪水旁9 小时前
UML函数原型中stereotype的含义,有啥用?
c++·uml
青草地溪水旁9 小时前
UML函数原型中guard的含义,有啥用?
c++·uml
执子手 吹散苍茫茫烟波10 小时前
LCR 076. 数组中的第 K 个最大元素
leetcode·排序算法