03-树2 List Leaves (25分)
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
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
4 1 5
我看的一位大佬的博客:这个有详细的解释https://blog.csdn.net/u013505811/article/details/93497550
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAXSIZE 10
int head;
int intputNums;
struct treeNode{
int left;
int right;
}tree[MAXSIZE];
typedef struct treeQueue
{
int *trees;
int front,rear;
}*tQueue;
tQueue creatQueue(){
tQueue q=(tQueue)malloc(sizeof(struct treeQueue));
q->trees=(int*)malloc(MAXSIZE*sizeof(int));
q->front=q->rear=-1;
return q;
}
void addQueue(tQueue q,int x)
{
if((q->rear+1)%10==q->front)
return;
else
{
q->rear=(q->rear+1)%MAXSIZE;
q->trees[q->rear]=x;
}
}
int deleteQueue(tQueue q)
{
if(q->front==q->rear)
return -1;
else
{
q->front=(q->front+1)%MAXSIZE;
return q->trees[q->front];
}
}
int readTree(int count)
{
int testArr[MAXSIZE];
char left,right;
for(int i=0;i<count;i++)
{
testArr[i]=0;
}
for(int i=0;i<count;i++)
{
getchar();
scanf("%c %c",&left,&right);
if(left!='-')
{
tree[i].left=left-'0';
testArr[tree[i].left]=1;
}else tree[i].left=-1;
if(right!='-'){
tree[i].right=right-'0';
testArr[tree[i].right]=1;
}else
tree[i].right=-1;
}
for(int i=0;i<count;i++)
{
if(!testArr[i]) return i;
}
return -1;
}
void traverseTree(int top)
{
int i;
int num=0;
if(top==-1)
return;
tQueue q=creatQueue();
addQueue(q,top);
while(q->front!=q->rear)
{
num++;
i=deleteQueue(q);
if(tree[i].left!=-1&&tree[i].right!=-1)
{
addQueue(q,tree[i].left);
addQueue(q,tree[i].right);
}
else if(tree[i].left!=-1&&tree[i].right==-1)
{
addQueue(q,tree[i].left);
}
else if(tree[i].left==-1&&tree[i].right!=-1)
{addQueue(q,tree[i].right);
}
else
{
if(num!=intputNums) printf("%d ",i);
else printf("%d",i);
}
}
}
int main()
{
scanf("%d",&intputNums);
head=readTree(intputNums);
traverseTree(head);
return 0;
}