1020 Tree Traversals (25分)
后序+中序转层序
node保存结点标号,按标号升序输出
//#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct node
{
int id;//按完全二叉树的下标
int val;//值
};
bool cmp(node a, node b)
{
return a.id < b.id;
}
vector<int> post, in;// postorder sequence// inorder sequence
vector<node> tree;
void preOrder(int root,int start,int end,int id)
{
if (start > end)return;
int index = start;
while (in[index] != post[root])index++;
tree.push_back({id,post[root]});//根
preOrder(root - end + index - 1,start, index - 1, 2 * id + 1);//左//id从0开始
preOrder(root - 1, index + 1, end, 2 * id + 2);//右
return;
}
int main()
{
//freopen("input.txt", "r", stdin);
int n;
cin >> n;
post.resize(n);
in.resize(n);
for (int i = 0; i < n; i++)
cin >> post[i];
for (int i = 0; i < n; i++)
cin >> in[i];
preOrder(n - 1, 0, n - 1,0);
sort(tree.begin(),tree.end(),cmp);//按下标输出
cout << tree[0].val;
for (int i = 1; i < tree.size(); i++)
cout << " "<<tree[i].val;
return 0;
}