题目
思路
先利用后序和中序序列构造二叉树
然后利用BFS遍历二叉树,其中记录深度,深度为偶数的时候正序输出,否则逆序输出
代码
#include <iostream>
#include <vector>
using namespace std;
vector<int> in, post;
typedef struct node {
int val;
node* lchild, * rchild;
}*Tree;
void Init(Tree& root,int cur,int low,int high) {
if (low > high)
return;
root = new node();
root->val = post[cur];
root->lchild = root->rchild = nullptr;
int _index = low;
while (_index <= high && in[_index] != post[cur]) _index++;
int len = high - _index;
Init(root->lchild,cur - 1 - len, low, _index - 1);
Init(root->rchild,cur - 1, _index + 1, high);
}
void BFS(Tree& root) {
queue<Tree> q;
vector<int> vec;
q.emplace(root);
Tree cur = root;
int depth = 1;
while (!q.empty()) {
Tree tmp = q.front();
vec.emplace_back(tmp->val);
q.pop();
if (tmp->lchild != nullptr)
q.emplace(tmp->lchild);
if (tmp->rchild != nullptr) {
q.emplace(tmp->rchild);
}
if (tmp == cur) {
if (tmp == root) {
cout << tmp->val;
}
else {
if (depth % 2 == 0) {
for (int i = 0; i < vec.size(); ++i)
cout << " " << vec[i];
}
else {
for (int i = vec.size() - 1; i >= 0; --i)
cout << " " << vec[i];
}
}
vec.clear();
if(!q.empty())
cur = q.back();
depth++;
}
}
}
int main()
{
int n;
cin >> n;
in.resize(n);
post.resize(n);
for (int i = 0; i < n; ++i) cin >> in[i];
for (int i = 0; i < n; ++i) cin >> post[i];
Tree t = nullptr;
Init(t,n-1,0,n-1);
BFS(t);
return 0;
}