传送门http://poj.org/problem?id=2255
要点:先序第一个是根节点,第二个是左子树的根;根据先序的信息,在中序中找到根节点,左边部分为左子树,右边为右子树。以上对每个子树也成立,直到找到叶节点,递归实现即可。
代码附上:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 10000;
char pre[maxn]; //先序
char mid[maxn]; //中序
char left_child[maxn]; //记录左右子
char right_child[maxn];
int p; //先序指针
void build_tree(int s, int e, int x)
{
if(s == e) return ;
for(int i = s; i <= e ; i ++)
{
if(mid[i] == x)
{
if(i - 1 >= s)
{
left_child[x] = pre[++p];
build_tree(s, i - 1, pre[p]);
}
if(i + 1 <= e)
{
right_child[x] = pre[++p];
build_tree(i + 1, e, pre[p]);
}
break;
}
}
}
void postorder(int i)
{
int left = left_child[i];
int right = right_child[i];
if(left != -1) postorder(left);
if(right != -1) postorder(right);
if(left == -1 && right == -1)
{
printf("%c",i);
return;
}
printf("%c",i);
return;
}
int main()
{
while(scanf("%s %s",pre, mid) == 2)
{
p = 0;
memset(left_child, -1, sizeof(left_child));
memset(right_child, -1, sizeof(right_child));
build_tree(0, strlen(pre) - 1, pre[0]);
postorder(pre[0]);
printf("\n");
}
return 0;
}