根据一颗二叉树的先序序列和中序序列来构造二叉树,并后序遍历输出
#include <iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
typedef char ElemType;
typedef struct node{
ElemType data;
struct node *lchild;
struct node *rchild;
}BTNode;
//根据先序序列和中序序列,来构造二叉树
BTNode *CreateBT1(ElemType *pre,ElemType *in,int n){
BTNode *b;
ElemType *p;
if(n<=0)return NULL;
b=(BTNode*)malloc(sizeof(BTNode));
b->data=*pre;
for(p=in;p<in+n;p++){
if(*p==*pre)break;
}
int k=p-in;
b->lchild=CreateBT1(pre+1,in,k);
b->rchild=CreateBT1(pre+1+k,p+1,n-k-1);
return b;
}
//后序遍历二叉树
void PostOrder(BTNode *b){
if(b!=NULL){
PostOrder(b->lchild);
PostOrder(b->rchild);
cout<<b->data;
}
}
int main() {
ElemType pre[]="ABDGCEF";
ElemType in[]="DGBAECF";
BTNode* b;
b=CreateBT1(pre,in,strlen(pre));
PostOrder(b);
return 0;
}
不妥之处,请多多指教。