ProgramAlgTrain/20240919/CSP常考算法模板/树的先序排列.cpp

40 lines
775 B
C++
Raw Normal View History

2024-09-19 02:22:41 +00:00
#include <bits/stdc++.h>
using namespace std;
void preOrder(string in,string post){
if(in.length() == 0) {
return;
}
char root=post[post.size()-1];
cout<<root; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD>
int k=in.find(root);
//<2F>ݹ<EFBFBD><DDB9><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
preOrder(in.substr(0, k), post.substr(0, k));
preOrder(in.substr(k+1), post.substr(k, in.size()-k-1));
}
void postOrder(string pre, string in)
{
if (pre.length() == 0) {
return;
}
char root = pre[0];
int k = in.find(root);
//<2F>ݹ<EFBFBD><DDB9><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
postOrder(pre.substr(1, k), in.substr(0, k));
postOrder(pre.substr(k+1), in.substr(k+1));
putchar(root); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD>
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
string inOrder, postOrder;
cin>>inOrder>>postOrder;
preOrder(inOrder, postOrder);
cout<<endl;
return 0;
}