【问题描述】
https://www.acwing.com/problem/content/description/1591/
【算法分析】
二叉搜索树的中序遍历结果为所给定结点值的升序排列(二叉搜索树中没有相同关键字的结点)。
因此,若想利用给定的结点值构建二叉搜索树,可先将给定的结点值按升序排列,然后在树的中序遍历的经典递归实现方法基础上略加改造,完成二叉搜索树相应结点的插入。
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int N=110;
int n, l[N], r[N], w[N], q[N];
int a[N];
void dfs(int u, int& k) {
if(u==-1) return ;
else {
dfs(l[u], k);
w[u]=a[k++];
dfs(r[u], k);
}
}
void bfs() {
int hh=0, tt=0;
q[0]=0;
while(hh<=tt) {
int t=q[hh++];
if(l[t]!=-1) q[++tt]=l[t];
if(r[t]!=-1) q[++tt]=r[t];
printf("%d ",w[t]);
}
}
int main() {
scanf("%d", &n);
for(int i=0; i<n; i++)
scanf("%d%d", &l[i], &r[i]);
for(int i=0; i<n; i++)
scanf("%d", &a[i]);
sort(a, a+n);
int k=0;
dfs(0,k);
bfs();
return 0;
}
/*
in:
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
out:
58 25 82 11 38 67 45 73 42
*/
【参考文献】
https://www.acwing.com/problem/content/description/1591/
https://www.acwing.com/solution/content/48278/