数据结构--叶子问题

来源:互联网 发布:老是找不到东西知乎 编辑:程序博客网 时间:2024/04/30 12:51

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

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

dfguli
#include<stdio.h>#include<malloc.h>#include<string.h>struct node{char data;struct node *l,*r;};char st[100];int i;struct node *creat(){struct node *root;char x;x=st[i++];if(x==',')return NULL;else{root=(struct node *)malloc(sizeof(struct node));root->data=x;root->l=creat();root->r=creat();}return root;}void cengci(struct node *root){struct node *p[100];p[0]=root;int front=0,rear=1;while(front<rear){if(p[front]){if(p[front]->l==NULL&&p[front]->r==NULL)printf("%c",p[front]->data);p[rear++]=p[front]->l;p[rear++]=p[front]->r;}front++; }}int main(){int n,j;struct node *root;while(scanf("%s",st)!=EOF){i=0;root=creat();cengci(root);printf("\n");}return 0;}
#include<stdio.h>
#include<malloc.h>
#include<string.h>
struct node
{
char data;
struct node *l,*r;
};
char st[100];
int i;
struct node *creat()
{
struct node *root;
char x;
x=st[i++];
if(x==',')
return NULL;
else
{
root=(struct node *)malloc(sizeof(struct node));
root->data=x;
root->l=creat();
root->r=creat();
}
return root;
}
void cengci(struct node *root)
{
struct node *p[100];
p[0]=root;
int front=0,rear=1;
while(front<rear)
{
if(p[front])
{
if(p[front]->l==NULL&&p[front]->r==NULL)

printf("%c",p[front]->data);
p[rear++]=p[front]->l;
p[rear++]=p[front]->r;

}
front++; 
}
}
int main()
{
int n,j;
struct node *root;
while(scanf("%s",st)!=EOF)
{
i=0;
root=creat();
cengci(root);
printf("\n");
}
return 0;
}
0 0
原创粉丝点击