您的位置:首页 > 其它

03-树1. List Leaves (25)

2015-05-05 12:52 441 查看


03-树1. List Leaves (25)

时间限制

400 ms

内存限制

65536 kB

代码长度限制

8000 B

判题程序

Standard

作者

CHEN, Yue

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


#include<stdio.h>
#include<stdlib.h>
#define MaxSize 20
int input(void){
char c;
do{
c = getchar();
}while(c != '-' && (c<'0' || c>'9'));
if(c == '-')
return -1;
else
return c-'0';
}
struct node
{
int left;
int right;
};
int main(){
void InOutQueue(int* p,struct node* tree,int* star,int* end);
int num,i,head,j[20];
int point=0;
for(i=0;i<10;i++){j[i]=-1;}
char temp;
//	struct node *tree;
scanf("%d",&num);
//	tree=(struct node *)malloc(num*sizeof(struct node));
struct node tree[15];
for(i=0;i<num;i++){
tree[i].left= input();
if(tree[i].left!=-1)
j[tree[i].left]=1;
tree[i].right= input();
if(tree[i].right!=-1)
j[tree[i].right]=1;
}

//j[tree[i].right]=-1;

for(i=0;i<num;i++){
if(j[i]==-1){
head=i;
break;
}
}

int queue[num+1],star = -1,end = 0;
queue[0] = -1;
queue[num] = -1;

queue[end] = head;
end++;

while(1!= end -star){
InOutQueue(queue,tree,&star,&end);
}

}
void InOutQueue(int* p,struct node* tree,int* star,int* end){
int t = p[(*star)+1];
static int P = 0;
if(tree[t].left!=-1){
p[*end] = tree[t].left;
(*end)++;
}
if(tree[t].right!=-1){
p[*end] = tree[t].right;
(*end)++;
}
if(tree[t].left == -1 && tree[t].right == -1){
if(!P){
printf("%d",t);
P = 1;
}else
printf(
4000
" %d",t);
}
(*star)++;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: