题目给出树的先序遍历和中序遍历,求树的后序遍历.
最初的思路是构造出来一棵树,然后进行后序遍历求解,但是构造树我卡了...就思考如果跳过建树过程。
大概思路就是在中序序列中找到前序序列的根结点,将中序序列分为左右两部分,然后继续划分知道只有一个节点,将其进入队列(貌似直接输出也行),两部分都找完之后输出此时的根...是个递归过程
代码貌似写的很挫
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
queue<char> q;
char s1[30],s2[30];
int x;
void dfs(int l,int r)
{
if(l>r)
return ;
if(l==r)
{
x++;
q.push(s1[x]);
return ;
}
x++;
for(int i=l;i<=r;i++)
{
if(s2[i]==s1[x])
{
dfs(l,i-1);
dfs(i+1,r);
q.push(s2[i]);
return ;
}
}
return ;
}
int main()
{
while(cin>>s1>>s2)
{
while(!q.empty())
q.pop();
x=-1;
int len=strlen(s1);
dfs(0,len-1);
while(!q.empty())
{
char ans=q.front();
q.pop();
printf("%c",ans);
}
printf("\n");
}
return 0;
}