示例代码:
#include<iostream>
using namespace std;
struct BTNode
{
int key;
BTNode *lchild;
BTNode *rchild;
};
BTNode * constructtree1(int *spre,int *epre,int *sinorder,int *einorder) //已知先序、中序求后序
{
int rootValue=spre[0];
BTNode *r=new BTNode();
r->key=rootValue;
r->lchild=r->rchild=NULL;
int *rootInorder=sinorder;
while(rootInorder<=einorder && *rootInorder!=rootValue)
++rootInorder;
int length=rootInorder-sinorder;
int * leftpreorderEnd=spre+length;
if(length>0)
{
r->lchild=constructtree1(spre+1,leftpreorderEnd,sinorder,rootInorder-1);
}
if(length<epre-spre)
{
r->rchild=constructtree1(leftpreorderEnd+1,epre,rootInorder+1,einorder);
}
return r;
}
BTNode *constructtree2(int *sinorder,int *einorder,int *epostorder,int *spostorder) //已知后序、中序求先序
{
int rootValue=epostorder[0];
BTNode * root=new BTNode();
root->key=rootValue;
root->lchild=root->rchild=NULL;
int * rootInorder=sinorder;
while(rootInorder<=einorder && *rootInorder!=rootValue)
++rootInorder;
int length=rootInorder-sinorder;
if(length>0)
{
root->lchild=constructtree2(sinorder,rootInorder-1,spostorder+length-1,spostorder);
}
if(length<epostorder-spostorder)
{
root->rchild=constructtree2(rootInorder+1,einorder,epostorder-1,spostorder+length);
}
return root;
}
void preorder(BTNode *r)
{
if(r==NULL)
return;
cout<<r->key<<endl;
preorder(r->lchild);
preorder(r->rchild);
}
int main()
{
int a[10]={1,2,4,7,3,5,6,8};
int b[10]={4,7,2,1,5,3,8,6};
int c[10]={7,4,2,5,8,6,3,1};
BTNode *s;
//s=constructtree1(a,a+7,b,b+7);
s=constructtree2(b,b+7,c+7,c);
preorder(s);
return 0;
}