中序和前序建立二叉树
//main.cpp
#include<iostream>
using namespace std;
typedef char TElemType;
typedef struct node
{
TElemType data;
struct node *lchild;
struct node *rchild;
}BiTNode,*BinTree;
BiTNode *creatBinTree(TElemType *VLR,TElemType *LVR,int n)//由中序序列和前序序列构造二叉树
{
if(n==0)
return NULL;
int k=0;
while(VLR[0]!=LVR[k])
k++;
BiTNode *t=new BiTNode;
if(t==NULL)
{
cerr<<"存储分配失败!"<<endl;
exit(0);
}
t->data=VLR[0];
t->lchild=creatBinTree(VLR+1,LVR,k);//从前序VLR+1开始对中序序列的左子序列0~k-1的k个元素递归建立左子树
t->rchild=creatBinTree(VLR+k+1,LVR+k+1,n-k-1);//从前序VLR+1+k开始对中序序列的右子序列k+1~n-1的n-k+1个元素递归建立右子树
return t;
}
void ClearBinTree(BinTree &T)//摧毁一棵树
{
if(T!=NULL)
{
ClearBinTree(T->lchild);
ClearBinTree(T->rchild);
delete T;T=NULL;
}
}
void PostOrder(BiTNode *T)
{
if(T!=NULL)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
cout<<T->data<<'\t';
}
}
void main()
{
TElemType *VLR=new TElemType[20];TElemType *LVR=new TElemType[20];int number;
cout<<"请输入前序序列:"<<endl;
cin>>VLR;
cout<<"请输入中序序列:"<<endl;
cin>>LVR;
BiTNode *T=creatBinTree(VLR,LVR,strlen(VLR));
PostOrder(T);
cout<<endl;
}
/*
ABHFDECKG
HBDFAEKCG
*/