您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树七:叶子问题

2017-03-22 21:09 169 查看


数据结构实验之二叉树七:叶子问题

Time Limit: 1000MS Memory Limit: 65536KB

Submit Statistic Discuss


Problem Description

已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。


Input

 输入数据有多行,每一行是一个长度小于50个字符的字符串。


Output

 按从上到下从左到右的顺序输出二叉树的叶子结点。


Example Input

abd,,eg,,,cf,,,
xnl,,i,,u,,



Example Output

dfg
uli

#include <bits/stdc++.h>
using namespace std;
struct node
{
char data;
node *l ,*r;
};
char s[100];
int cnt;
struct node *creat()
{
struct node *t;
if(s[++cnt] == ',')
{
return NULL;
}
else
{
t = new node;
t->data = s[cnt];
t->l = creat();
t->r = creat();
return t;
}
};
void pre(node *root)
{
if(root)
{
printf("%c",root->data);
pre(root->l);
pre(root->r);
}
}
int sum;
void leaf(node *root)
{
if(root)
{
if(root->l == NULL&& root->r == NULL)
sum++;
leaf(root->l);
leaf(root->r);
}
}
void bfs(node *root)
{
queue<node*>q;
if(root!=NULL)
q.push(root);
while(!q.empty())
{
node * u = q.front();
q.pop();
if(u->l == NULL&& u->r == NULL )
printf("%c",u->data);
if(u->l != NULL)
q.push(u->l);
if(u->r != NULL)
q.push(u->r);
}
}
int main()
{

while(~scanf("%s",s))
{
cnt = -1;
sum = 0;
struct node * root = creat();
bfs(root);
printf("\n");
//printf("%d\n",sum);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: