这个题算是02的简化版,会了02这个题写起来很轻松,下面附上ac代码
# include<stdio.h>
# include<queue>
using namespace std;
struct tree
{
int number;
int left;
int right;
}t[11];
int n;
int a[10];
int inputtree()
{
char le,ri;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
getchar();
scanf("%c %c", &le, &ri);
t[i].number = i;
if (le == '-')
{
t[i].left = -1;
}
else
{
t[i].left = le - '0';
a[t[i].left] = 1;
}
if (ri == '-')
{
t[i].right = -1;
}
else
{
t[i].right = ri - '0';
a[t[i].right] = 1;
}
}
for (int i = 0; i < n; i++)
{
if (a[i] != 1)
{
return i;
}
}
return -1;
}
void outputtree(int n)
{
int flag = 1;
queue<int>q;
q.push(n);
while (!q.empty())
{
int q1 = q.front();
q.pop();
if (t[q1].left == -1 && t[q1].right == -1)
{
if (flag)
{
printf("%d", t[q1].number);
flag = 0;
}
else
{
printf(" %d", t[q1].number);
}
}
if (t[q1].left != -1)
{
q.push(t[q1].left);
}
if (t[q1].right != -1)
{
q.push(t[q1].right);
}
}
}
int main(void)
{
int head = inputtree();
if (head == -1)
{
printf("\n");
return 0;
}
outputtree(head);
return 0;
}