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 NNN (≤10\le 10≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1N-1N−1. Then NNN 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>
#define MaxSize 10
#define Tree int
#define Null -1
struct TreeNode{
int Left,Right;
}T[MaxSize];
//create tree ,return root
Tree BuildTree(T[])
{
int n;
scanf("%d\n",&n);
int check[MaxSize];
for(int i=0;i<MaxSize;i++) check[i]=0;
for(int i=0;i<n;i++){
char a,b;
scanf("%c %c\n",&a,&b);
if(a!='-'){
T[i].Left=a-'0';
check[T[i].Left]=1;
}
else{
T[i].Left=Null;
}
if(b!='-'){
T[i].Right=b-'0';
check[T[i].Right]=1;
}
else{
T[i].Right=Null;
}
}
int i=-1;
for(i=0;i<n;i++){
if(!check[i]) break;
}
return i;
}
void LevelLeaf(Tree root)
{
int flag=0;
int queue[MaxSize];
int front=0,rear=0;//front point temp,rear point next;
queue[rear++]=root;
while(front<rear){
Tree temp=queue[front++];
if(T[temp].Left==Null && T[temp].Right == Null){
if(flag==0) flag=1;
else printf(" ");
printf("%d",temp);
}
if(T[temp].Left!=Null) queue[rear++]=T[temp].Left;
if(T[temp].Right!=Null) queue[rear++]=T[temp].Right;
}
}
int main()
{
freopen("in.txt","r",stdin);
Tree root=BuildTree(T);
LevelLeaf(root);
}