Description
已知一个按先序输入的字符序列,如abd,eg,cf,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
Input
输入数据有多行,每一行是一个长度小于50个字符的字符串。
Output
按从上到下从左到右的顺序输出二叉树的叶子结点。
Sample
Input
abd,eg,cf,
xnl,i,u,
Output
dfg
uli
Hint
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
char data;
struct node *l, *r;
} Tree;
char pre[55];
int cnt;
Tree *creat()
{
Tree *root;
if(pre[cnt] == ',')
{
cnt++;
root = NULL;
}
else
{
root = new Tree;
root->data = pre[cnt++];
root->l = creat();
root->r = creat();
}
return root;
}
void cengxu_leaves(Tree *root)//模拟队列
{
Tree *que[1000];
int i = 0, j = 0;
que[i++] = root;
while(i > j)
{
if(que[j])
{
que[i++] = que[j]->l;
que[i++] = que[j]->r;
if(que[j]->l == NULL && que[j]->r == NULL)
printf("%c", que[j]->data);
}
j++;
}
}
/*void cengxu_leaves(Tree *root)//STL中的queue
{
Tree *temp;
queue<Tree *>q;
q.push(root);
while(!q.empty())
{
temp = q.front();
q.pop();
if(temp)
{
if(!temp->l && !temp->r)
{
printf("%c", temp->data);
}
if(temp->l)
q.push(temp->l);
if(temp->r)
q.push(temp->r);
}
}
}*/
int main()
{
while(~scanf("%s", pre))
{
cnt = 0;
Tree *root = creat();
cengxu_leaves(root);
printf("\n");
}
return 0;
}