数据结构实验之二叉树七:叶子问题
Time Limit: 1000MS Memory limit: 65536K
题目描述
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
输入
输入数据有多行,每一行是一个长度小于50个字符的字符串。
输出
按从上到下从左到右的顺序输出二叉树的叶子结点。
示例输入
abd,,eg,,,cf,,, xnl,,i,,u,,
示例输出
dfg uli
提示
来源
xam
示例程序
#include<bits/stdc++.h>
using namespace std;
struct Tree
{
char c;
Tree *L,*R;
};
Tree* Creat()
{
Tree *p=new Tree;
p->L=NULL;
p->R=NULL;
return p;
}
int num;
char s[10000],ss[10000];
Tree * Build(Tree* root,int r)
{
if(num>r)
return 0;
if(s[num]==',')
return 0;
root=Creat();
root->c=s[num];
num++;
root->L=Build(root->L,r);
num++;
root->R=Build(root->R,r);
//if(!root->L&&root->R) //叶子数
//ans++;
return root;
}
int BFS(Tree *root)
{
queue<Tree*>Q;
Q.push(root);
while(!Q.empty())
{
Tree* p=Q.front();
Q.pop();
if(!p)
return 0;
//printf("%d",p->c);//中序遍历
if(p->L)
Q.push(p->L);
if(p->R)
Q.push(p->R);
if(!p->L&&!p->R)
printf("%c",p->c);
}
}
int main()
{
while(~scanf("%s",s))
{
num=0;
int len=strlen(s);
Tree* root=Creat();
root=Build(root,len-1);
BFS(root);
printf("\n");
}
return 0;
}