数据结构实验之二叉树七:叶子问题
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;
typedef struct node
{
char data;
struct node *ltree,*rtree;
} *lit;
int len,t;
string s;
void creat_tree(lit &p)//建立二叉树
{
if(s[t]==',')
{
p=NULL;
t++;
if(t==len) return ;
}
else
{
p=new node;
p->data=s[t];
t++;
if(t==len)
return ;
creat_tree(p->ltree);
creat_tree(p->rtree);
}
}
void level(lit &p)
{
queue<lit>q;
if(p)
q.push(p);//根节点入队列
while(!q.empty())
{
p=q.front();
if(!p->ltree&&!p->rtree)
cout<<p->data;
else
{
if(p->ltree)
q.push(p->ltree);//左子树入队列
if(p->rtree)
q.push(p->rtree);//右子树入队列
}
q.pop();
}
}
int main()
{
lit p;
while(cin>>s)
{
t=0;
len=s.size();
creat_tree(p);
level(p);
cout<<endl;
}
return 0;
}