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 1 - - - 0 - 2 7 - - - - 5 - 4 6Sample Output:
4 1 5
1.我觉得这个题的难点还是在对题意的理解给出从节点0到节点N-1的各个左右孩子,画出二叉树图如下:
2.二叉树构建好后用队列直接层序遍历就好。
#include<stdio.h>
typedef struct bintree{
int data,Ileft,Iright;
}Bintree;
void InOutQueue(int* p,Bintree* tree,int* star,int* end);
int input(void);
int main(){
// 定义及初始化
int n,i;
scanf("%d",&n);
Bintree BinTree[n];
int chack[n],boot;
int queue[n+1],star = -1,end = 0;
queue[0] = -1;
queue[n] = -1;
for(i = 0;i<n;i++)
chack[i] = 0;
// 给节点的左右孩子赋值,若为'-'则赋值为-1
for(i = 0;i<n;i++){
BinTree[i].data = i;
BinTree[i].Ileft = input();
if(BinTree[i].Ileft != -1)
chack[BinTree[i].Ileft] = 1;
BinTree[i].Iright = input();
if(BinTree[i].Iright != -1)
chack[BinTree[i].Iright] = 1;
}
// 查找根节点
for(i = 0;i<n;i++)
if(!chack[i])
boot = i;
// 根节点入队
queue[end] = boot;
end++;
// 进行一系列入队出队操作
while(1!= end -star){
InOutQueue(queue,BinTree,&star,&end);
}
return 0;
}
void InOutQueue(int* p,Bintree* tree,int* star,int* end){
int t = p[(*star)+1];
static int P = 0;
if(tree[t].Ileft!=-1){
p[*end] = tree[t].Ileft;
(*end)++;
}
if(tree[t].Iright!=-1){
p[*end] = tree[t].Iright;
(*end)++;
}
if(tree[t].Ileft == -1 && tree[t].Iright == -1){
if(!P){
printf("%d",t);
P = 1;
}else
printf(" %d",t);
}
(*star)++;
}
int input(void){
char c;
do{
c = getchar();
}while(c != '-' && (c<'0' || c>'9'));
if(c == '-')
return -1;
else
return c-'0';
}