本题算是二叉树与搜索的结合体。
题意就是:根据所给的两串序列,分别是前序和中序,求出二叉树的后序。
思想:首先是从先序,在中序中找到根节点,插入到二叉树当中,标记这个字符已经被插入。然后根据刚才所插入的根节点,在中序中查询该节点两旁是否有还没插入的点(标记的用处),以确定是否需要建立左子树和右子树。如果要建立的话,继续从先序中,找到下一个节点,再在中序中找到该节点,插入二叉树……递归循环即可。
*递归结束:两边的字符都已经标记为已插入,则return。如果是当前节点为边缘的,自己特殊处理一下。
AC代码:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
const int p = 30;
char bTree[p<<15];
char s1[p],s2[p];
bool visit [p];//according to s2
int len,loc_s1;
void build(int rt)
{
int loc;
for(int i=0;i < len;i++)
{
if(s1[loc_s1]==s2[i])
{
loc_s1++;
loc = i;\
break;
}
}
bTree[rt] = s2[loc];//insert current node to the binary tree;
visit[loc] = 1;
if((loc == 0&&visit[loc+1])||(loc== (len-1)&&visit[loc-1]))
return;
else if(visit[loc-1]&&visit[loc+1])
return;
if(loc != 0&& !visit[loc-1]) build(rt<<1);
if(loc != len-1&&!visit[loc+1]) build(rt<<1|1);
}
void query(int rt)
{
if(bTree[rt] == '*')
return;
query(rt<<1);//L
query(rt<<1|1);//R
printf("%c",bTree[rt]);
}
int main()
{
while(scanf("%s%s",s1,s2)!=EOF)
{
memset(bTree,'*', sizeof(bTree));
//getchar();//get the Enter
loc_s1 = 0,len = strlen(s1);
memset(visit, 0, sizeof(visit));
build(1);
query(1);
puts("");
}
return 0;
}