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;
    }
};
相关推荐
bkspiderx10 分钟前
C++设计模式之行为型模式:状态模式(State)
c++·设计模式·状态模式
会开花的二叉树29 分钟前
分布式文件存储 RPC 服务实现
c++·分布式·网络协议·rpc
abcd_zjq1 小时前
VS2026+QT6.9+opencv图像增强(多帧平均降噪)(CLAHE对比度增强)(边缘增强)(图像超分辨率)
c++·图像处理·qt·opencv·visual studio
Algebraaaaa2 小时前
Qt中的字符串宏 | 编译期检查和运行期检查 | Qt信号与槽connect写法
开发语言·c++·qt
nju_spy4 小时前
力扣每日一题(二)任务安排问题 + 区间变换问题 + 排列组合数学推式子
算法·leetcode·二分查找·贪心·排列组合·容斥原理·最大堆
代码对我眨眼睛4 小时前
226. 翻转二叉树 LeetCode 热题 HOT 100
算法·leetcode·职场和发展
黑色的山岗在沉睡5 小时前
LeetCode 494. 目标和
算法·leetcode·职场和发展
Predestination王瀞潞7 小时前
IO操作(Num22)
开发语言·c++
宋恩淇要努力8 小时前
C++继承
开发语言·c++
江公望10 小时前
Qt qmlRegisterSingletonType()函数浅谈
c++·qt