前序中序求后序
代码:
#include <map>
#include <cmath>
#include <cstdio>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define met(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
const int maxn = 1e3+10;
char preorder[maxn],inorder[maxn];
void find(char *preorder,char *inorder,int len)
{
if(len==0)
return;
char temp=*preorder;
int rootindex=0;
while(temp!=inorder[rootindex]&&rootindex<len)
rootindex++;
// 找到根节点。
find(preorder+1,inorder,rootindex);//left
find(preorder+rootindex+1,inorder+rootindex+1,len-rootindex-1);//right
printf("%c",temp);
return;
}
int main()
{
scanf("%s%s",preorder,inorder);
int len=strlen(preorder);
find(preorder,inorder,len);
printf("\n");
}
后序中序求前序
代码:
#include <map>
#include <cmath>
#include <cstdio>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define met(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
const int maxn = 1e3+10;
char postorder[maxn],inorder[maxn];
void findpre(char *inorder,char *postorder,int len)
{
if(len==0)
return;
char temp=postorder[len-1];
int rootindex=len-1;
while(temp!=inorder[rootindex]&&rootindex>=0)
rootindex--;
findpre(postorder,inorder,rootindex);//left
findpre(postorder+rootindex,inorder+rootindex+1,len-rootindex-1);//right
printf("%c",temp);
return;
}
int main()
{
scanf("%s%s",inorder,postorder);
int len=strlen(postorder);
findpre(inorder,postorder,len);
printf("\n");
}