已知前序、中序求后序
#include <stdio.h>
void PreAndInToPost(char *preorder,char *inorder,int lenth)
{
if(lenth==0)
return;
char temp=*preorder;
int rootindex=0;
while(*preorder!=inorder[rootindex]&&rootindex<lenth)
rootindex++;
PreAndInToPost(preorder+1,inorder,rootindex);//left
PreAndInToPost(preorder+rootindex+1,inorder+rootindex+1,lenth-rootindex-1);//right
putchar(temp);
return;
}
int main()
{
char* pr="GDAFEMHZ";
char* in="ADEFGHMZ";
PreAndInToPost(pr,in,8);
return 0;
}
已知后序、中序求前序
#include <stdio.h>
void PostAndInToPre(char *postorder,char *inorder,int lenth)
{
if(lenth==0)
return;
putchar(postorder[lenth-1]);
int rootindex=lenth-1;
while(postorder[lenth-1]!=inorder[rootindex]&&rootindex>=0)
rootindex--;
PostAndInToPre(postorder,inorder,rootindex);//left
PostAndInToPre(postorder+rootindex,inorder+rootindex+1,lenth-rootindex-1);//right
return;
}
int main()
{
char* post="AEFDHZMG";
char* in="ADEFGHMZ";
PostAndInToPre(post,in,8);
return 0;
}