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;
    }
};
相关推荐
anew___6 小时前
蜂鸣器播放音乐——让 Arduino 唱出旋律
c++·stm32·单片机·嵌入式硬件·c
stolentime8 小时前
洛谷P10515 转圈题解
c++·算法·数学建模·贪心算法
tdtsmt9 小时前
穿戴硬件量产工艺实录:天地通电子智能手表主板 SMT 贴片案
c++
土司大王11 小时前
LeetCode hot100 回溯专题总结:Java 通用模板、决策树模型
java·算法·leetcode·决策树
m0_7345717612 小时前
深入理解C++ 析构函数<一>基本概念
开发语言·c++
t-think13 小时前
C++ string 类(上)—— string类初识与常用接口详解
开发语言·c++
a1879272183113 小时前
【算法】链表(二):链表上的双指针——变速、异链与定距,和一份路程账本
数据结构·算法·leetcode·链表·go·指针·环形链表
cpp_learners13 小时前
C++ 实现责任链模式(Chain of Responsibility):从一堆 if-else 到可插拔的处理管道
开发语言·c++·责任链模式
郝学胜_神的一滴13 小时前
C++11 工程级应用 12:编译期类型魔法,干掉重复与臃肿的代码
c++·visual studio