思路
在中序序列循环一遍找到根节点,根节点其实就是后序遍历的最后一个节点。这样就将中序遍历划分为左右子树,在左右子树里面分别重复之前的操作。
code
#include <bits/stdc++.h>
using namespace std;
string in,post;
void preorder(int root,int st,int ed){
if(st>ed) return;
int i;
for(i=st;i<=ed;i++) if(in[i]==post[root]) break;
cout<<post[root];
preorder(root-1-ed+i,st,i-1);//左子树
preorder(root-1,i+1,ed);//右子树
}
int main(){
cin>>in>>post;
preorder((int)in.length()-1,0,(int)in.length()-1);
return 0;
}