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;
    }
};
相关推荐
fqbqrr1 分钟前
2601C++,复制超文本格式
c++
m0_561359674 分钟前
基于C++的机器学习库开发
开发语言·c++·算法
2401_8324027512 分钟前
C++中的类型擦除技术
开发语言·c++·算法
2301_7634724622 分钟前
C++网络编程(Boost.Asio)
开发语言·c++·算法
踩坑记录39 分钟前
leetcode hot100 23. 合并 K 个升序链表 hard 分治 迭代
leetcode·链表
轩情吖1 小时前
Qt的窗口
开发语言·c++·qt·窗口·工具栏·桌面级开发
L186924547821 小时前
无外设条件下的自动找眼V2
c++
hcnaisd21 小时前
深入理解C++内存模型
开发语言·c++·算法
李老师讲编程1 小时前
C++信息学奥赛练习题-杨辉三角
数据结构·c++·算法·青少年编程·信息学奥赛
期末考复习中,蓝桥杯都没时间学了1 小时前
力扣刷题13
数据结构·算法·leetcode