Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
Input
输入数据有多行,每一行是一个长度小于50个字符的字符串。
Output
按从上到下从左到右的顺序输出二叉树的叶子结点。
Sample Input
abd,,eg,,,cf,,, xnl,,i,,u,,
Sample Output
dfg uli
Hint
Source
xam
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//树的存储结构
typedef struct node
{
char ch ;
struct node *left ;
struct node *right ;
}Tree ;
char str[55] ; //记录输入的数据
int cmd ;
//建树函数
Tree *creat()
{
if(str[cmd++] == ',')
{
return NULL ;
}
else
{
Tree *root = (Tree*)malloc(sizeof(Tree)) ;
root->ch = str[cmd-1] ;
root->left = creat() ;
root->right = creat() ;
return root ;
}
}
//层次遍历
void chengci(Tree *root)
{
Tree *q[40000] ; //构建队列
//开始时,队列为空
int front = 0 ;
int rear = 0 ;
Tree *t ; //一个中间变量来接受栈顶元素元素
if(root)
{
q[rear++] = root;
}
while(rear!=front)
{
t = q[front++] ;
if(t)
{
if(t->left == NULL && t->right == NULL)
printf("%c",t->ch) ;
q[rear++] = t->left;
q[rear++] = t->right ;
}
}
}
int main()
{
Tree *root ;
while(~scanf("%s",str))
{
cmd = 0 ; //保证每次都是从第一个元素来建树
root = creat() ;
chengci(root) ;
printf("\n") ;
}
return 0 ;
}