这个写的有点麻烦了,最后对应用的map
其实中序遍历的时候边遍历边写入会简洁很多
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
using namespace std;
const int maxn = 1e3 + 10;
int tree[maxn][2], n, s[maxn];
vector<int>inorder, levelorder;
map<int, int>m;
void inor(int index)
{
if (index == -1)return;
inor(tree[index][0]);
inorder.push_back(index);
inor(tree[index][1]);
}
void levleor(int root)
{
queue<int>q;
q.push(root);
while (!q.empty())
{
int top = q.front();
q.pop();
levelorder.push_back(top);
if (tree[top][0] != -1)q.push(tree[top][0]);
if (tree[top][1] != -1)q.push(tree[top][1]);
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d%d", &tree[i][0], &tree[i][1]);
for (int i = 0; i < n; i++)scanf("%d", &s[i]);
inor(0);
levleor(0);
sort(s, s + n);
for (int i = 0; i < n; i++)m[inorder[i]] = s[i];
for (int i = 0; i < n; i++)printf("%d%s", m[levelorder[i]], i == n - 1 ? "\n" : " ");
return 0;
}