数据结构实验之二叉树七:叶子问题
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
Input
输入数据有多行,每一行是一个长度小于
50
个字符的字符串。
Output
按从上到下从左到右的顺序输出二叉树的叶子结点。
Example Input
abd,,eg,,,cf,,, xnl,,i,,u,,
Example Output
dfg uli
#include<stdio.h>
#include<malloc.h>
#define N 10005
char data[N];
typedef struct Tree{
char data;
struct Tree * Left;
struct Tree * Right;
}Tree;
Tree * Queue[N];
int rear=0;
int front=0;
void CreateTree(Tree **root){//先序创建树
if(data[front]==','){
*root=NULL;
front++;
}
else{
(*root)=(Tree *)malloc(sizeof(Tree));
(*root)->data=data[front++];
CreateTree(&(*root)->Left);
CreateTree(&(*root)->Right);
}
}
void LevelShow(Tree * root){//层次遍历
if(root){
Tree * p= root;
while(front<=rear){
if(!p->Left&&!p->Right){
printf("%c",p->data);
}
if(p->Left){
Queue[rear++]=p->Left;
}
if(p->Right){
Queue[rear++]=p->Right;
}
p=Queue[front++];
}
}
}
int main(){
while(scanf("%s",data)!=EOF){
Tree * root=NULL;
CreateTree(&root);
front=0;
LevelShow(root);
printf("\n");
front=0;
rear=0;
}
return 0;
}