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

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

2018-03-11 20:52 281 查看

Problem Description

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

Input

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

Output

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

Example Input

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

Example Output

dfg
uli

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char s;
struct node *l, *r;
};
int k;
char s1[100];
struct node *build()
{
struct node *root;
char a;
a = s1[k++];
if(a == ',')
return NULL;
else
{
root = (struct node *)malloc(sizeof(struct node));
root->s = a;
root->l = build();
root->r = build();
}
return root;
};
void leaf(struct node *root)
{
int i = 0, j = 0;
struct node *p[100];
p[j++] = root;
while(i < j)
{
if(p[i])
{
if(!p[i]->l && !p[i]->r)
printf("%c", p[i]->s);
p[j++] = p[i]->l;
p[j++] = p[i]->r;
}
i++;
}
printf("\n");
}
int main()
{
struct node *root;
while(scanf("%s", s1) != EOF)
{
k = 0;
root = build();
leaf(root);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: