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 (≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. 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:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
4 1 5
思路:
1、结构数组模拟
2、通过层次遍历来输出叶节点
#include <stdlib.h>
#include <stdio.h>
#define MaxN 10
#define Null -1
#define ERROR -1
struct node{
int left, right;
}T[MaxN]; //用结构数组表示树
int check[MaxN]; //检测根节点
//队列
typedef int Position;
typedef int ElementType;
typedef struct QNode *Queue;
struct QNode{
ElementType * Data;
Position Front, Rear;
int MaxSize;
};
Queue CreateQueue( int MaxSize ){
Queue Q = (Queue)malloc(sizeof(struct QNode));
Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
Q->Front = Q->Rear = 0;
Q->MaxSize = MaxSize;
return Q;
}
bool IsFull( Queue Q ){
return ((Q->Rear + 1) % Q->MaxSize == Q->Front);
}
bool AddQ( Queue Q, ElementType X ){
if( IsFull(Q) ) {
printf("queue is full\n");
return false;
}
else {
Q->Rear = (Q->Rear + 1) % Q->MaxSize;
Q->Data[Q->Rear] = X;
return true;
}
}
bool IsEmpty( Queue Q ) {
return (Q->Front == Q->Rear);
}
ElementType DeleteQ( Queue Q ) {
if( IsEmpty(Q) ) {
printf("queue is empty\n");
return ERROR;
}
else {
Q->Front = (Q->Front + 1) % Q->MaxSize;
return Q->Data[Q->Front];
}
}
//建树
int makeTree(struct node T[]){
int n, i, root = -1;
char cl, cr;
scanf("%d", &n);
getchar();
if(n){
/*for(i = 0; i < n; i++)
check[i];*/ //这题只建立一棵树,所以不必重置
for(i = 0; i < n; i++){
scanf("%c %c", &cl, &cr);
getchar();
if(cl != '-'){
T[i].left = cl - '0';
check[T[i].left] = 1;
}
else
T[i].left = Null;
if(cr != '-'){
T[i].right = cr - '0';
check[T[i].right] = 1;
}
else
T[i].right = Null;
}
for(i = 0; i < n; i++)
if(!check[i]) break;
root = i;
}
return root;
}
//访问叶结点
//void listLeaves(int R){
// if(R != Null){
// if(T[R].left == Null && T[R].right == Null)
// printf("%d", R);
// listLeaves(T[R].left);
// listLeaves(T[R].right);
// }
//}
//由于要由上到下,由左到右输出,所以用层序遍历改编
void listLeaves(int R){
Queue Q;
int cnt = 0;
if(R == Null) return ;
Q = CreateQueue(MaxN);
AddQ(Q, R);
while ( !IsEmpty( Q ) ) {
R = DeleteQ( Q );
if(T[R].left == Null && T[R].right == Null){
cnt++;
if( cnt != 1 ) printf(" ");
printf("%d", R);
}
if(T[R].left != Null) AddQ(Q, T[R].left);
if(T[R].right != Null) AddQ(Q, T[R].right);
}
}
int main(){
int R;
R = makeTree(T);
listLeaves(R);
system("pause");
return 0;
}