层序走到第四个是谁
运行下面这段程序:
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
struct TNode {
string name;
TNode* left = nullptr;
TNode* right = nullptr;
};
TNode* build() {
TNode* root = new TNode{"总部"};
root->left = new TNode{"华北"};
root->right = new TNode{"华南"};
root->left->left = new TNode{"北京"};
root->left->right = new TNode{"天津"};
root->right->right = new TNode{"广州"};
return root;
}
int main() {
queue<TNode*> q;
q.push(build());
vector<string> order;
while (!q.empty()) {
TNode* node = q.front();
q.pop();
order.push_back(node->name);
if (node->left != nullptr) q.push(node->left);
if (node->right != nullptr) q.push(node->right);
}
cout << order[3] << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论