03 - 树 2. List Leaves (25)


Given a tree,
you are supposed to list all the leaves in the order of top down,
and left to right.
Input Specification:
Each input file contains one test case.
For each case, the first line gives a positive integer N (<=10)
which is the total number of nodes in the tree --
and hence the nodes are numbered from 0 to N-1.
Then N lines follow, each corresponds to a node,
and gives the indices of the left and right children of the node.
If the child does not exist,
a "-" will be put at the position.
Any pair of children are separated by a space.
Output Specification:
For each test case,
print in one line all the leaves' indices in the order of top down,
and left to right.
There must be exactly one space between any adjacent numbers,
and no extra space at the end of the line.


Sample Input:
8
1 -

0 -
2 7

5 -
4 6



Sample Output:
4 1 5

define MAXNODE 100

typedef struct{
int index;
char lchild;
char rchild;
}TNode;




int main()
{
int num,i,j;
int c;
scanf("%d",&num);
TNode a[num];
//存放输入的节点左右孩子
for(i=0;i //将输入结点放入数组
{
while((c=getchar())==' '||c=='\t'||c=='\n');
a[i].lchild=c;
while((c=getchar())==' '||c=='\t'||c=='\n');
a[i].rchild=c;
a[i].index=i;
}
int findroot[num];
//用来寻找root
for(i=0;i //初始化,默认为-1
findroot[i]=-1;
for(i=0;i //遍历数组左右孩子,没出现的数字就是root代表的结点,
//即它不是其它结点的孩子
{
if('0'<=a[i].lchild&&a[i].lchild<='9')
findroot[a[i].lchild-'0']=1;
//(1用来标记出现过的)
if('0'<=a[i].rchild&&a[i].rchild<='9')
findroot[a[i].rchild-'0']=1;
}
int root;
for(i=0;findroot[i]!=-1;i++);
//-1代表上述遍历未找到的结点
root=i;
TNode node;
TNode queue[MAXNODE];
int front=0,rear=-1;
queue[++rear]=a[root];
int index[num];
i=0;
while(rear-front>=0)
//层次遍历
{
node=queue[front++];
if(node.lchild=='-'&&node.rchild=='-')
index[i++]=node.index;
//按顺序记录无孩子的结点
if(node.lchild!='-')
queue[++rear]=a[node.lchild-'0'];
if(node.rchild!='-')
queue[++rear]=a[node.rchild-'0'];
}
for(j=0;j< i;j++) //输出
{
printf("%d",index[j]);
if(j< i-1)
putchar(' ');
else
break;
}
return 0;
}

你可能感兴趣的:(03 - 树 2. List Leaves (25))