由先序中序、中序后序构造二叉树![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/16bf8e4245e857f84293882b42264dd4.png)
#include<iostream>
using namespace std;
# define MaxSize 20
typedef char ElemType;
typedef struct node{
ElemType data;
struct node*lchild;
struct node*rchild;
}BTNode,*BTree ;
void DestroyBTree(BTNode*&b){
if(b!=NULL){
DestroyBTree(b->lchild);
DestroyBTree(b->rchild);
delete b;
}
}
void DispBTree(BTNode* b){
if(b!=NULL){
cout<<b->data;
if(b->lchild||b->rchild){
cout<<"(";
DispBTree(b->lchild);
if(b->rchild) cout<<",";
DispBTree(b->rchild);
cout<<")";
}
}
}
void displayBTree(BTNode* T){
BTree stack[100],p;
int level[100],top,n,i;
if(T!=NULL){
top=1;
stack[top]=T;
level[top]=3;
while(top>0){
p=stack[top];
n=level[top];
for(i=1;i<=n;i++)
cout<<" ";
cout<<" "<<p->data<<" ";
//for(i=n+1;i<100-n;i+=2)
//printf("-");
cout<<endl;
top--;
if(p->rchild!=NULL){
top++;
stack[top]=p->rchild;
level[top]=n+3;}
if(p->lchild!=NULL){
top++;
stack[top]=p->lchild;
level[top]=n+3;
}
}
}
}
BTNode*CreateBT1(char*pre,char*in,int n){
BTNode*b;
char *p;
int k;
if(n<=0) return NULL;
b= new BTNode;
b->data=*pre;
for(p=in;p<in+n;p++)
if (*p==*pre)
break;
k=p-in;
b->lchild=CreateBT1(pre+1,in,k);
b->rchild=CreateBT1(pre+1+k,p+1,n-k-1);
return b;
}
BTNode*CreateBT2(char*post,char*in,int n){
BTNode*b;
char r,*p;
int k;
if(n<=0) return NULL;
r=*(post+n-1);
b= new BTNode;
b->data=r;
for(p=in;p<in+n;p++)
if (*p==r)
break;
k=p-in;
b->lchild=CreateBT2(post,in,k);
b->rchild=CreateBT2(post+k,p+1,n-k-1);
return b;
}
int main(){
char* pre="ABDEHJKLMNCFGI";
char* in="DBJHLKMNEAFCGI";
char* post="DJLNMKHEBFIGCA";
BTNode* b,*c;
cout<<"先序遍历 "<<pre<<endl;
cout<<"中序遍历 "<<in<<endl;
cout<<"后序遍历 "<<post<<endl;
cout<<"先序,中序创建子树"<<endl;
b=CreateBT1(pre,in,14);
DispBTree(b);
cout<<endl;
cout<<"后序,中序创建子树"<<endl;
c=CreateBT2(post,in,14);
DispBTree(c);
cout<<endl;
displayBTree(b);
DestroyBTree(b);
DestroyBTree(c);
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2942ab5ba622db6308d9ef0073b51b65.png)