根据二元树后序序列建立二叉树

来源:互联网 发布:金融大数据发展历程 编辑:程序博客网 时间:2024/05/29 19:56
typedef struct BiTNode{char value;struct BiTNode *lchild;struct BiTNode *rchild;}BiTNode,*BiTree;char* lookL(char str[],int& len){int i=0;for(;i<len;i++){if(str[i]>str[len]){break;}}std::string str1=str;str1=str1.substr(0,i);//cout<<str1.c_str()<<endl;char* p=(char*)malloc(i+1);strcpy(p,str1.c_str());len=str1.length()-1;return p;}char* LookR(char str[],int &len){int i=0;for(;i<len;i++){if(str[i]>str[len]){break;}}std::string str1=str;str1=str1.substr(i,len-i);char* p=(char*)malloc(len-i+1);strcpy(p,str1.c_str());len=str1.length()-1;return p;}void createBiTree(BiTree &t,char str[],int len){if(len<0){t=NULL;return;}t=(BiTree)malloc(sizeof(BiTNode));t->value=str[len];t->lchild=NULL;t->rchild=NULL;char* p0=(char*)malloc(sizeof(char)*20);memset(p0,0,20);p0=lookL(str,len);createBiTree(t->lchild,p0,len);char* p1=(char*)malloc(sizeof(char)*20);memset(p1,0,20);std::string test;test=str;len=test.length()-1;p1=LookR(str,len);createBiTree(t->rchild,p1,len);}void traverse(BiTree T){if(T){traverse(T->lchild);cout<<T->value<<" ";traverse(T->rchild);}}int main(){char str1[]="132576984";char* str=(char*)malloc(sizeof(char)*8);strcpy(str,str1);BiTree T=NULL;createBiTree(T,str,8);traverse(T);return 0;}

以下是测试: