先序序列与中序序列可以确定一颗二叉树。
思想是:在先序序列中第一个是根结点的值,对应中序序列找到对应结点值,其左边是左子树的中序序列,右边是右子树的中序序列,根据左边个数确定先序序列的左子树部分,右子树同理。
可用递归与非递归实现,一切可用递归实现的算法借助栈总能实现。
A[]是先序序列,B[]是中序序列,l1,h1,l2,h2分别为第一个和最后一个结点下标
初始调用时l1=l2=1;h1=h2=n.
非递归算法:
typedef struct
{ int l1 ,h1, l2, h2;
BiTree t;
}node;void preincreat(ElemType A[],B[], int l1,h1,l2,h2)
{
BiTree bt;
int top=0; stack<node>s;
int i;
node p;
bt=(BiTree)malloc(sizeof(BiTNode));
p.l1=l1;p.l2=l2;p.h1=h1;p.h2=h2;p.t=bt;
s[++top]=p;
while(top>0)
{
p=s[top--];
bt=p.t;l1=p.l1;h1=p.h1;l2=pl.l2;h2=p.h2;
for(i=l2;i<=h2;i++)
if(B[i]==A[l1])break;//找到中序中查根结点的值
bt->data=A[l1];
if(i==l2)bt->lchild=null;//无左子树
else
{
bt->lchild=(BiTree)malloc(sizeof(BiTNode));
p.t=bt->lchild;
p.l1=l1+1; p.h1=l1+i-l2;
p.l2=l2; p.h2=i-1;
s[++top]=p;
}
if(i==h2) bt->rchild=null;//无右子树
else
{
bt->rchild=(BiTree)malloc(sizeof(BiTNode));
p.t=bt->rchild;
p.l1=l1+i-l2+1; p.h1=h1;
p.l2=i+1; p.h2=h2;
s[++top]=p;
}
}/while
}
递归算法:
void preincreat(ElemType A[],B[], int l1,h1,l2,h2,BiTree bt)
{ int i;
for(i=l2;i<=h2;i++)
if(B[i]==A[l1]) break;
bt->data=A[l1];
if(i==l2)
bt-lchild=null;
else
{ int Ll1=l1+1;int Lh1=l1+i-l2;
int Ll2=l2;int Lh2=i-1;
preincreat(A,B,Ll1,Lh1,Ll2,Lh2,bt->lchild);
}
if(i==h2)
bt-rchild=null;
else
{ int Rl1=l1+i-l2+1;int Rh1=h1;
int Rl2=i+1;int Rh2=h2;
preincreat(A,B,Rl1,Rh1,Rl2,Rh2,bt->rchild);
}
}
如有错误,请求指出。