叶子问题

来源:互联网 发布:如何关淘宝店铺 编辑:程序博客网 时间:2024/06/02 10:47

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

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

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

示例输出

dfg

uli

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

0 0