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

来源:互联网 发布:网络诽谤罪如何取证 编辑:程序博客网 时间:2024/06/05 02:26

题目描述

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

输入

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

输出

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

示例输入

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

示例输出

dfguli
#include<iostream>#include<cstring>using namespace std;int len,key;char ch[1992];typedef struct node{    char data;    struct node *lchild,*rchild;} Tree;Tree *creat(Tree *root){    if(key<len)    {        char c=ch[key++];        if(c==',')            return NULL;        else        {            root=new Tree();            root->data=c;            root->lchild=creat(root->lchild);            root->rchild=creat(root->rchild);        }    }    return root;}int main(){    int in,out,i;    while(cin>>ch)    {        Tree *root,*p,*leaf[1000];        key=0;        len=strlen(ch);        root=creat(root);        in=0;        out=0;        leaf[in++]=root;        while(out<in)        {            p=leaf[out++];            if(p)//再存的时候,我建议最好加上一句判断,别把空节点也存进去。            {                if(p->lchild==NULL&&p->rchild==NULL)                    cout<<p->data;                leaf[in++]=p->lchild;                leaf[in++]=p->rchild;            }        }        cout<<endl;    }    return 0;}

0 0
原创粉丝点击