1. 先序和中序确定一棵树
BtNode * CreateTreePI(ElemType *ps,ElemType *is,int n)
{
if(NULL == ps || NULL == is || n < 1)
{
return NULL;
}
else
{
return CreatePI(ps,is,n);
}
}
BtNode * CreatePI (ElemType *ps,ElemType *is,int n)
{
BtNode *s = NULL;
if(n > 0)
{
s = Buynode();
s->data = ps[0];
int pos = FindIs(is,n,ps[0]);
if(-1 == pos) exit(1);
s->leftchild = CreatePI(ps+1,is,pos);
s->rightchild = CreatePI(ps+pos+1,is+pos+1,n-pos-1);
}
return s;
}
int FindIs(ElemType *is,int n,ElemType val)
{
int pos = -1;
for(int i = 0;i<n;++i)
{
if(is[i] == val)
{
pos = i;
break;
}
}
return pos;
}
2. 后序和中序确定一棵树
BtNode * CreateTreeIL(ElemType *is,ElemType *ls,int n)
{
if(NULL == is || NULL == ls || n < 1)
return NULL;
else
return CreateIL(is,ls,n);
}
BtNode * CreateIL(ElemType *is,ElemType *ls,int n)
{
BtNode *s = NULL;
if(n > 0)
{
s = Buynode();
s->data = ls[n-1];
int pos = FindIs(is,n,ls[n-1]);
if(-1 == pos) exit(1);
s->leftchild = CreateIL(is,ls,pos);
s->rightchild = CreateIL(is+pos+1,ls+pos,n-pos-1);
}
return s;
}