题目:输入一棵二叉树,按照从上到下,从左到右的顺序输出该二叉树。
相邻节点之间用一个空格隔开,每棵树的输入用一对空括号()结束。
注意:如果从根到某个节点的路径上有的节点没有在输入中给出,或者给出超过一次,应当输出-1.节点个数不超过256
样例输入:
(11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
(3,L) (4,R) ()
样例输出:
5 4 8 11 13 4 7 2 1
-1
本题是UVA122原题,有需要的可以去UVA查看。
#include<cstdio>
#include<cstring>
int check(int i,int *t){
while(i!=1){
i/=2;
if(t[i]==0)
return 1;
}
return 0;
}
int main()
{
char s[7];
int t[300];
int i,flag,f,count=0;
memset(t,0,sizeof(t));
while(1){
scanf("%s",s);
if(s[0]=='('&&s[1]==')')
break;
int x=0;
i=1;
while(s[i]!=',')
x=x*10+s[i++]-'0';
f=1;
flag=0;
if(s[++i]==')'){
if(t[1]==0)
t[1]=x;
else
flag=1;
}
while(s[i]!=')'){
if(s[i++]=='L')
f=f*2;
else
f=f*2+1;
}
if(t[f]!=0&&f!=1)
flag=1;
if(flag)break;
t[f]=x;
count=f>count?f:count;
}
if(!t[1])flag=1;
for(i=1;i<=count;i++){
if(t[2*i]==0&&t[2*i+1]==0&&t[i]!=0)
flag=check(i,t);
if(flag)break;
}
if(!flag){
for(i=1;i<=count;i++){
if(t[i]!=0)
printf("%d ",t[i]);
}
printf("\n");
}
else
printf("-1\n");
return 0;
}原文:http://blog.csdn.net/u014492609/article/details/44599089