数据结构实验之二叉树七:叶子问题
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic Discuss
Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
Input
输入数据有多行,每一行是一个长度小于50个字符的字符串。
Output
按从上到下从左到右的顺序输出二叉树的叶子结点。
Sample Input
abd,,eg,,,cf,,,
xnl,,i,,u,,
Sample Output
dfg
uli
Hint
Source
xam
#include<stdio.h>
#include<stdlib.h>
struct tree
{
char data;
struct tree*left,*right;
}*link[54],*root;
char s[54];
int ans;
struct tree*front_create()
{
struct tree*root;
char c=s[ans++];
if(c==',')root=NULL;
else
{
root=(struct tree*)malloc(sizeof(struct tree));
root->data=c;
root->left=front_create();
root->right=front_create();
}
return root;
}
void ceng(struct tree*root)
{
if(root)
{
int i=0,j=0;
link[j++]=root;
while(i<j)
{
if(link[i])
{
if(link[i]->left==NULL&&link[i]->right==NULL)
printf("%c",link[i]->data);
else
{
link[j++]=link[i]->left;
link[j++]=link[i]->right;
}
}
i++;
}
}
}
int main()
{
while(~scanf("%s",s))
{
ans=0;
struct tree*root;
root=front_create();
ceng(root);
printf("\n");
}
return 0;
}
在层序遍历上加个条件就可以