AcWing 1589. 构建二叉搜索树
原题链接
中等
作者:
回归线
,
2021-04-27 22:26:59
,
所有人可见
,
阅读 279
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 110;
int w[N], l[N], r[N];
int a[N];
queue<int> q;
void dfs(int u, int& k) {
if (u == -1) {
return;
}
dfs(l[u], k);
w[u] = a[k++];
dfs(r[u], k);
}
void bfs() {
q.push(0);
while (!q.empty()) {
int t = q.front();
q.pop();
cout << w[t] << " ";
if (l[t] != -1) {
q.push(l[t]);
}
if (r[t] != -1) {
q.push(r[t]);
}
}
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i ++ ) {
cin >> l[i] >> r[i];
}
for (int i = 0; i < n; i ++ ) {
cin >> a[i];
}
sort(a, a + n);
int k = 0;
dfs(0, k);
bfs();
return 0;
}