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 NN (\le 10≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N-1N−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
使用层序遍历的方法。
#include<stdio.h>
#include<stdlib.h>
#define MaxTree 10
#define ElementType int
#define Tree int
#define Null -1
struct TreeNode{
ElementType Element;
Tree Left;
Tree Right;
}T[MaxTree];
int BuildTree(){
int i,N;
char cl,cr;
//printf("enter N:");
scanf("%d",&N);
InitializeTree(N);
ReadTree(N);
return N;
//initial Tree
}
void InitializeTree(int N){
struct TreeNode *TreePointer;
for(int i=0;i<N;i++){
TreePointer=&T[i];
TreePointer->Element=i;
TreePointer->Left=-1;
TreePointer->Right=-1;
//printf("e:%d l:%d r:%d\n",TreePointer->Element,TreePointer->Left,TreePointer->Right);
}
}
//read Tree
void ReadTree(int N){
char cl,cr;
int i;
struct TreeNode *TreePointer;
for(i=0;i<N;i++){
TreePointer=&T[i];
//printf("enter[%d] left & right :",i);
scanf(" %c",&cl);
scanf(" %c",&cr);
if(cl!='-'){
TreePointer->Left=cl-'0';
}
if(cr!='-'){
TreePointer->Right=cr-'0';
}
}
return 0;
}
void PrintTree(int N){
for(int i=0;i<N;i++)printf("e:%d l:%d r:%d\n",T[i].Element,T[i].Left,T[i].Right);
}
int findRoot(int N){
int i,j,root;
root = 0;
for(i=0;i<N;i++){
for(j=0;j<N;j++){
//printf("T[%d].Left:%d T[%d].Right:%d T[%d].Element:%d\n",j,T[j].Left,j,T[j].Right,root,T[root].Element);
if(T[j].Left==T[root].Element||T[j].Right==T[root].Element){
//printf("root changed");
root = j;
break;
}
}
}
return root;
}
void Leaves(int N,int root){
int a[N],i,j=0;
a[0]=root;
int flag=0;
for(int i=0;i<N;i++){
//printf("a[%d] :%d\n",i,a[i]);
//printf("e:%d l:%d r:%d\n",T[a[i]].Element,T[a[i]].Left,T[a[i]].Right);
if(T[a[i]].Left!=-1){
j++;
a[j]=T[a[i]].Left;
}
if(T[a[i]].Right!=-1){
j++;
a[j]=T[a[i]].Right;
}
if(T[a[i]].Left==-1&&T[a[i]].Right==-1){
if(flag==0){
printf("%d",a[i]);
flag=1;
}else printf(" %d",a[i]);
}
}
}
int main(){
int root,N;
N = BuildTree(&T);
//PrintTree(N);
root=findRoot(N);
//printf("root:%d\n",root);
Leaves(N,root);
system("pause");
return 0;
}