题目链接:
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3170
题意:
给你一个n,里面有n个点,然后再给出一个m,下面有m-1行的数据,每一行的数据个数是不定的,需要自己计算输入。但是大致上是这样给的,每一行都会给出父结点的左子树的结点的总个数,以及右子树结点的个数。这样,会构成一颗二叉搜索树,让你以后序遍历的方式输出这颗树。
题解:
解决好输入的问题( 第一行的输入一定只有两个,第二行开始的输入的个数,可以通过找上一行中2出现的个数*2),然后就是以深搜递归的方式去确定,这里就不详细讲了,直接看代码。
代码:
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define met(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
const int maxn = 1000+10;
queue<int>q[maxn];
int num[maxn];
int ans[maxn];
void dfs(int left,int right,int cnt,int a,int b,int MM,int MX)
{
ans[right]=num[MM+a];
if(a==1)
{
ans[left]=num[MM+a-1];
}
else if(a>=2)
{
int depth=cnt+1;
int tempa=0,tempb=0;
tempa=q[depth].front();
q[depth].pop();
tempb=q[depth].front();
q[depth].pop();
dfs(left,left+a-1,depth,tempa,tempb,MM,MM+a-1);
}
if(b==1)
{
ans[right-1]=num[MM+a+1];
}
else if(b>=2)
{
int depth=cnt+1;
int tempa=0,tempb=0;
tempa=q[depth].front();
q[depth].pop();
tempb=q[depth].front();
q[depth].pop();
dfs(left+a,right-1,depth,tempa,tempb,MM+a+1,MX);
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;i++)
{
while(!q[i].empty())
q[i].pop();
}
met(ans,0);
for(int i=1;i<=n;i++)
scanf("%d",&num[i]);
sort(num+1,num+1+n);
int m;
scanf("%d",&m);
if(n==1)
{
printf("%d\n",num[1]);
continue;
}
m-=1;
int cnt=1;
int next_cnt=0;
int len=0;
while(m--)
{
cnt*=2;
next_cnt=0;
while(cnt--)
{
int x=0;
scanf("%d",&x);
q[len].push(x);
if(x>=2)
next_cnt++;
}
len++;
cnt=next_cnt;
}
int ans1=q[0].front();
q[0].pop();
int ans2=q[0].front();
q[0]. pop();
dfs(1,n,0,ans1,ans2,1,n);
for(int i=1;i<=n;i++)
{
printf("%d",ans[i]);
if(i!=n)
printf(" ");
else
printf("\n");
}
}
}