本题与1064一模一样的思路,建树时统计当前节点左子树的节点数量,以此确定当前节点的num值。
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
typedef long long ll;
const int maxn = 1e2+5,inf=1e9;
struct node
{
int num;
node *left=nullptr, *right=nullptr;
};
int n,r[maxn];
vector<pair<int, int>> T;
int count_node(int now)
{
if (now == -1)
return 0;
else
return count_node(T[now].first) + count_node(T[now].second) + 1;
}
node* creat_tree(int low, int high, int now)
{
if (now == -1)
return nullptr;
int left_num = count_node(T[now].first);
node *t = new node();
t->num = r[low + left_num];
t->left = creat_tree(low, low + left_num - 1, T[now].first);
t->right = creat_tree(low + left_num + 1, high, T[now].second);
return t;
}
void BFS(node *t)
{
queue<node *> q;
q.push(t);
while (!q.empty())
{
auto top = q.front();
q.pop();
cout << top->num;
if (--n)
cout << " ";
if (top->left != nullptr)
q.push(top->left);
if (top->right != nullptr)
q.push(top->right);
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
int a, b;
cin >> a >> b;
T.push_back(make_pair(a, b));
}
for (int i = 0; i < n; i++)
cin >> r[i];
sort(r, r + n);
node *t = creat_tree(0, n - 1, 0);
BFS(t);
return 0;
}