Sample Input:
9
1 6
2 3
-1 -1
-1 4
5 -1
-1 -1
7 -1
-1 8
-1 -1
73 45 11 58 82 25 67 38 42
Sample Output:
58 25 82 11 38 67 45 73 42
非常基本的数据结构题,做了几道题终于发现个一眼就会的题了,还是一遍过,难得
#include<bits/stdc++.h>
using namespace std;
struct node {
node* lc;
node* rc;
int val;
}nd[200];
int a[200];
int cnt = 0;
queue<node>q;
void midsearch(node *point)
{
if (point == nullptr)
return;
midsearch(point->lc);
point->val = a[cnt++];
midsearch(point->rc);
}
void bfs()
{
q.push(*nd);
int flag = 0;
while (!q.empty())
{
if (flag)
cout << ' ';
flag = 1;
node tem = q.front();
cout << tem.val;
q.pop();
if (tem.lc != nullptr)
q.push(*(tem.lc));
if (tem.rc != nullptr)
q.push(*(tem.rc));
}
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int l, r;
cin >> l >> r;
if (l != -1)
nd[i].lc = nd + l;
if (r != -1)
nd[i].rc = nd + r;
}
for (int i = 0; i < n; i++)
cin >> a[i];
sort(a, a + n);
midsearch(nd);
bfs();
}