数据结构实验之二叉树七:叶子问题
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
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>
int i;
char s[60];
struct node
{
char data;
struct node *l, *r;
};
int max(int a, int b)
{
if(a > b) return a;
else return b;
}
struct node *creat()
{
struct node *root;
if(s[i++] == ',')
{
root = NULL;
}
else
{
root = (struct node*) malloc (sizeof(struct node));
root -> data = s[i - 1];
root -> l = creat();
root -> r = creat();
}
return root;
};
void yezi(struct node *root)
{
if(!root)
return;
struct node *q[100000], *p;
int f, r;
q[1] = root, f = r = 1;
while(f <= r)
{
p = q[f];
f++;
if(p -> l == NULL && p -> r == NULL)
printf("%c", p -> data);
if(p -> l != NULL)
{
r++;
q[r] = p -> l;
}
if(p -> r != NULL)
{
r++;
q[r] = p -> r;
}
}
}
int main()
{
while(~scanf("%s", s))
{
struct node *root;
root = creat();
i = 0;
yezi(root);
printf("\n");
}
return 0;
}