03-树2 List Leaves (25分)

来源:互联网 发布:win7 优化 编辑:程序博客网 时间:2024/05/12 08:12

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 NN (\le 1010) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N-1N1. Then NN 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:

81 -- -0 -2 7- -- -5 -4 6

Sample Output:

4 1 5

借鉴别人的代码,真是妙啊


#include<stdio.h>#include<ctype.h>struct node{int root;int left;int right;};int main(){int n,i;scanf("%d\n",&n);struct node tree[n];for(i=0;i<n;i++){tree[i].root=1;tree[i].left=-1;tree[i].right=-1;}char cl,cr;for(i=0;i<n;i++){scanf("%c %c",&cl,&cr);if(isdigit(cl)){tree[i].left=cl-'0';tree[cl-'0'].root=-1;}if(isdigit(cr)){tree[i].right=cr-'0';tree[cr-'0'].root=-1;}getchar();}int root;for(i=0;i<n;i++){if(tree[i].root==1){root=i;break;}}int queue[n];int head=0,rear=0;int flag=0;queue[rear++]=root;while(rear-head){int node=queue[head++];if(tree[node].left!=-1){queue[rear++]=tree[node].left;}if(tree[node].right!=-1){queue[rear++]=tree[node].right;}if(tree[node].left==-1&&tree[node].right==-1){if(flag==0){printf("%d",node);flag=1;}else{printf(" %d",node);}}}}


0 0