已知中序、后序,求先序
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <queue>
#include <cmath>
using namespace std;
string s1,s2;
void dfs(int l1,int r1,int l2,int r2)
{
int m = s1.find(s2[r2]);
cout<<s2[r2];
if(m>l1) dfs(l1,m-1,l2,m-l1+l2-1);
if(m<r1) dfs(m+1,r1,m-l1+l2,r2-1);
}
int main()
{
cin>>s1>>s2;
dfs(0,s1.length()-1,0,s2.length()-1);
return 0;
}
已知先序、中序,求后序
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <queue>
#include <cmath>
using namespace std;
string s1,s2;
// mid fir
void dfs(int l1,int r1,int l2,int r2)
{
int m = s2.find(s1[l1]);
if(m > l2) dfs(l1 + 1,l1 + m - l2,l2,m-1);
if(m < r2) dfs(l1 + m - l2 + 1,r1,m+1,r2);
cout<<s1[l1];
}
int main()
{
cin>>s1>>s2;
dfs(0,s2.length()-1,0,s1.length()-1);
return 0;
}