1 已知中序遍历和先序遍历,求后序遍历
洛谷P1827
#include<bits/stdc++.h>
using namespace std;
string s1,s2;
void fun(string ss1,string ss2){
if(ss1.size()==0||ss2.size()==0) return;
char rt = ss2[0];
int k = ss1.find(rt);
fun(ss1.substr(0,k),ss2.substr(1,k));
fun(ss1.substr(k+1),ss2.substr(k+1));
cout<<rt;
}
int main(){
cin>>s1>>s2;
fun(s1,s2);
return 0;
}
2 已知中序遍历和后序遍历,求先序遍历
洛谷P1030
#include<bits/stdc++.h>
using namespace std;
string s1,s2;
void fun(string s1,string s2){
if(s1.size()==0||s2.size()==0) return;
cout<<s2[s2.size()-1];
int k = s1.find(s2[s2.size()-1]);
string il,ir,pl,pr;
il = s1.substr(0,k);
pl = s2.substr(0,k);
fun(il,pl);
ir = s1.substr(k+1);
pr = s2.substr(k,s2.size()-1-k);
fun(ir,pr);
}
int main(){
cin>>s1>>s2;
fun(s1,s2);
return 0;
}