数据结构实验之二叉树七:叶子问题
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
Input
输入数据有多行,每一行是一个长度小于50个字符的字符串。
Output
按从上到下从左到右的顺序输出二叉树的叶子结点。
Sample Input
abd,,eg,,,cf,,,
xnl,,i,,u,,
Sample Output
dfg
uli
Hint
Source
xam
纯c代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char pre[55];
int l;
struct node
{
char data;
struct node *left;
struct node *right;
};
struct node *creat()
{
char p;
struct node *root;
p = pre[l++];
if(p == ',')
return NULL;
else
{
root = (struct node *)malloc(sizeof(struct node));
root -> data = p;
root -> left = creat();
root -> right = creat();
}
return root;
};
void leave(struct node *root) // 从上往下 从左往右 先判断层次 再判断是否是叶子
{
struct node *p[60];
int in = 0;
int out = 1;
p[0] = root;
while(in < out)
{
if(p[in])
{
if(p[in] -> left == NULL && p[in] -> right == NULL)
printf("%c", p[in] -> data);
p[out++] = p[in] -> left;
p[out++] = p[in] -> right;
}
in++;
}
}
int main()
{
struct node *root;
while(~scanf("%s", pre))
{
l = 0;
root = creat();
leave(root);
printf("\n");
}
return 0;
}