题目如下:
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
list leaves,只需要输出叶节点,从上到下从左到右层序遍历。需要用到队列。
#include<stdio.h>
#define MAX_N 10
struct tree{
int left;
int right;
}t1[MAX_N];
int InputTree(struct tree *tree){
int n;
char cl,cr;
int root=-1;
scanf("%d\n",&n);
int check[n];
if(n){
for(int i=0;i<n;i++) check[i]=0;
for(int i=0;i<n;i++){
scanf("%c %c\n",&cl,&cr);
if(cl!='-'){
t1[i].left=cl-'0';
check[t1[i].left]=1;
}else t1[i].left=-1;
if(cr!='-'){
t1[i].right=cr-'0';
check[t1[i].right]=1;
}else t1[i].right=-1;
}
for(root=n-1;root>=0;root--){
if(!check[root]) break;
}
}
return root;
}
void QueueAndPrint(struct tree tree[],int root){
int q[MAX_N];
int front=-1,rear=-1;
if(root!=-1){
q[++rear]=root;
while(front<rear&&rear<MAX_N){
int i=q[++front];//Pop
if(tree[i].left!=-1) q[++rear]=tree[i].left;
if(tree[i].right!=-1) q[++rear]=tree[i].right;
if(tree[i].left==-1&&tree[i].right==-1){
printf("%d",i);
if(rear!=front) printf(" ");
}
}
}
}
int main(){
int root;
root=InputTree(t1);
QueueAndPrint(t1,root);
return 0;
}