题意:
让你建一颗BST树并输出其层次遍历序列.
思路:
很简单的一个题目,首先要知道BST的中序遍历就一定是有序递增的序列.那么我们根据这个特性将给定的序列排序,然后按照根据所给的节点信息按照中序遍历的顺序来建树,最后在输出层次遍历序列即可.
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e2+5;
struct node
{
int l,r;
}a[maxn];
int n,ans[maxn];
int ord[maxn],cur,tmp[maxn];
void build(int pos)
{
if(pos == -1)
return ;
build(a[pos].l);
tmp[pos] = ans[cur++];
build(a[pos].r);
return ;
}
void bfs(int root)
{
queue<int>Q;
while(!Q.empty()) Q.pop();
Q.push(root);
int num = 0;
while(!Q.empty())
{
int p = Q.front();
Q.pop();
ord[num++] = tmp[p];
if(a[p].l != -1)
Q.push(a[p].l);
if(a[p].r != -1)
Q.push(a[p].r);
}
return ;
}
int main()
{
while(~scanf("%d",&n))
{
for(int i = 0;i < n;++i)
scanf("%d %d",&a[i].l,&a[i].r);
for(int i = 0;i < n;++i)
scanf("%d",&ans[i]);
sort(ans,ans + n);
cur = 0;
build(0);
bfs(0);
for(int i = 0;i < n;++i)
printf("%d%c",ord[i],i == n - 1?'\n':' ');
}
return 0;
}