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.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXSIZE 10
typedef int ElementType;
typedef int Position;
struct TreeNode{
ElementType Element;
Position Left;
Position Right;
}Tree[MAXSIZE];
struct QNode{
Position Element;
struct QNode * Next;
};
struct HeaderQNode{
struct QNode * Front;
struct QNode * Rear;
};
Position ReadTree(struct TreeNode Tree[])
{
int i,N;
scanf("%d",&N);
if(N==0) return -1;
int flag[N];
for(i=0;i<N;i++) flag[i]=0;
for(i=0;i<N;i++){
char c,cl,cr;
while( (c=getchar())!='\n' ) continue;
scanf("%c %c",&cl,&cr);
Tree[i].Element=i;
Tree[i].Left= (cl=='-')?(-1):cl-'0';
Tree[i].Right= (cr=='-')?(-1):cr-'0';
if(Tree[i].Left!=-1) flag[Tree[i].Left]=1;
if(Tree[i].Right!=-1) flag[Tree[i].Right]=1;
}
for(i=0;i<N;i++){
if(flag[i]==0) return i;
}
}
struct HeaderQNode * CreateQueue(void)
{
struct HeaderQNode * p;
p=(struct HeaderQNode *)malloc(sizeof(struct HeaderQNode));
p->Front=NULL;p->Rear=NULL;
return p;
}
void EnQueue(struct HeaderQNode * p,Position V)
{
struct QNode * temp=(struct QNode *)malloc(sizeof(struct QNode));temp->Element=V;
if(p->Rear==NULL){
p->Front=temp;
temp->Next=NULL;
p->Rear=temp;
}else {
p->Rear->Next=temp;
temp->Next=NULL;
p->Rear=temp;
}
}
bool IsEmpty(struct HeaderQNode * p)
{
if(p->Rear==NULL) return true;
else return false;
}
ElementType DeQueue(struct HeaderQNode * p)
{
Position ret;
if(!IsEmpty(p)){
struct QNode * temp=p->Front;
ret=temp->Element;
p->Front=temp->Next;
if(p->Front==NULL) p->Rear=NULL;
free(temp);
}else return 0;
return ret;
}
void LevelOrderTraversal(Position Root,struct TreeNode Tree[])
{
struct HeaderQNode * p=CreateQueue();
bool flag=true;
ElementType FirstInQueue;
EnQueue(p,Root);
while(!IsEmpty(p)){
FirstInQueue=p->Front->Element;
if(Tree[FirstInQueue].Left==-1 && Tree[FirstInQueue].Right==-1){
if(flag){
printf("%d",FirstInQueue);
flag=false;
}else
printf(" %d",FirstInQueue);
}
if(Tree[FirstInQueue].Left!=-1) EnQueue(p,Tree[FirstInQueue].Left);
if(Tree[FirstInQueue].Right!=-1) EnQueue(p,Tree[FirstInQueue].Right);
DeQueue(p);
}
}
int main()
{
Position Root;
Root=ReadTree(Tree);
LevelOrderTraversal(Root,Tree);
}