纯用结构体数组做的,粗略的写法还请勿怪。
#include <stdio.h>
#include <stdlib.h>
int flag = 0;
struct {
int left;
int right;
}num[15];
int array[15];//找树根。
int root;
void seek(int );
int count = 0;
int main()
{
int N;
scanf("%d",&N);
getchar();
char a,b;
char ch;
if(N==1)
{
scanf("%c%c%c",&a,&ch,&b);
printf("%d",'0'-'0');
}
else if(N>1)
{
for(int i = 0;i < N;i++)
{
scanf("%c%c%c",&a,&ch,&b);
getchar();
if(a>='0'&&a<='9')
{
num[count].left = a - '0';
array[a-'0'] = 1;//谁当儿子记下来。
}
else if(a == '-')num[count].left = -1;//无儿子都变负。
if(b>='0'&&b<='9')
{
num[count].right = b - '0';
array[b-'0'] = 1;//谁当儿子记下来。
}
else if(b == '-')num[count].right = -1;//无儿子都变负。
count++;
}
for(int i = 0;i < N;i++)
{
if(!array[i])
{
root = i;
break;
}
}
seek(root);
}
return 0;
}
void seek(int root)
{
int p;
int q[1000];
int head=0,tail=0;
if(num[root].left<0&&num[root].right<0)return;
if(num[root].left>=0||num[root].right>=0){
q[tail++] = root;
while(head!=tail){
p = q[head++];
if(num[p].left<0&&num[p].right<0)
{
if(flag)printf(" ");
else if(flag == 0)
{
flag = 1;
}
printf("%d",p);
}
if(num[p].left>=0)q[tail++]=num[p].left;
if(num[p].right>=0)q[tail++]=num[p].right;
}
}
}