Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
Input
输入数据有多行,每一行是一个长度小于50个字符的字符串。
Output
按从上到下从左到右的顺序输出二叉树的叶子结点。
Example Input
abd,,eg,,,cf,,, xnl,,i,,u,,
Example Output
dfg uli
code:
//因为是从上到下从左到右的顺序输出,可以看作是层序遍历的方法读取叶子节点,在层序遍历基础上更改就可以
#include<stdio.h>
#include<stdlib.h>
typedef struct Bitnode
{
char data;
struct Bitnode *lchild, *rchild;
}Bitree;
int cnt, count;
char t[51];
Bitree *creat()
{
Bitree *T;
if(t[++cnt] == ',') T = NULL;
else
{
T = (Bitree*)malloc(sizeof(Bitree));
T->data = t[cnt];
T->lchild = creat();
T->rchild = creat();
}
return T;
}
void readleaf(Bitree *T)
{
Bitree *temp[100];
int in = 0, out = 0;
temp[in++] = T;
while(in>out)
{
if(temp[out])
{
if((!temp[out]->lchild)&&(!temp[out]->rchild))
{
printf("%c", temp[out]->data);
}
temp[in++] = temp[out]->lchild;
temp[in++] = temp[out]->rchild;
}
out++;
}
}
int main()
{
while(~scanf("%s", t))
{
count = 0;
cnt = -1;
Bitree *T;
T = creat();
readleaf(T);
printf("\n");
}
}
#include<stdlib.h>
typedef struct Bitnode
{
char data;
struct Bitnode *lchild, *rchild;
}Bitree;
int cnt, count;
char t[51];
Bitree *creat()
{
Bitree *T;
if(t[++cnt] == ',') T = NULL;
else
{
T = (Bitree*)malloc(sizeof(Bitree));
T->data = t[cnt];
T->lchild = creat();
T->rchild = creat();
}
return T;
}
void readleaf(Bitree *T)
{
Bitree *temp[100];
int in = 0, out = 0;
temp[in++] = T;
while(in>out)
{
if(temp[out])
{
if((!temp[out]->lchild)&&(!temp[out]->rchild))
{
printf("%c", temp[out]->data);
}
temp[in++] = temp[out]->lchild;
temp[in++] = temp[out]->rchild;
}
out++;
}
}
int main()
{
while(~scanf("%s", t))
{
count = 0;
cnt = -1;
Bitree *T;
T = creat();
readleaf(T);
printf("\n");
}
}