前序中序还原二叉树:
struct node *creat(int len,char *str1,char *str2) //由先序序列和中序序列建立二叉树
{
int i;
struct node *root;
if(len==0)
return NULL;
root=(struct node*)malloc(sizeof(struct node));
root->date=str1[0];
for(i=0;i<len;i++) //找根节点在中序序列的位置
{
if(str2[i]==root->date)
break;
}
root->lchild=creat(i,str1+1,str2); //建立左子树
root->rchild=creat(len-i-1,str1+i+1,str2+i+1); //建立右子树
return root;
}
中序后序还原二叉树:
struct node *creat(int len,char *str2,char *str1)
{
int i;
struct node *root;
if(len==0)
return NULL;
root=(struct node*)malloc(sizeof(struct node));
root->date=str1[len-1];
for(i=0;i<len;i++)
{
if(str2[i]==root->date)
break;
}
root->lchild=creat(i,str2,str1);
root->rchild=creat(len-i-1,str2+i+1,str1+i);
return root;
}
总结:对函数设置3个变量len,str1,str2(len,str2,str1)分别储存序列长度,第一个序列首地址,第二个序列首地址。函数中找到根节点位置用i储存,最后通过递归建立左右子树(注意:函数变量中左右子树的地址为第一个字母的地址!)