正经题解 | 先序排列
2024-07-17 19:54:17
发布于:广东
11阅读
0回复
0点赞
构造二叉树即可
#include<bits/stdc++.h>
using namespace std;
void f(string a,string b){
int len=a.size();
if(len==0){
return ;
}
int pos=a.find(b[len-1]);
cout<<b[len-1];
f(a.substr(0,pos),b.substr(0,pos));
f(a.substr(pos+1,len-pos-1),b.substr(pos,len-pos-1));
}
int main(){
string a,b;
cin>>a>>b;
f(a,b);
return 0;
}
以下是AC助手修改后的代
#include <iostream>
#include <string>
using namespace std;
// 重构先序遍历
void reconstructPreorder(const string& inorder, const string& postorder) {
if (inorder.empty()) {
return;
}
int pos = inorder.find(postorder.back());
cout << postorder.back();
reconstructPreorder(inorder.substr(0, pos), postorder.substr(0, pos));
reconstructPreorder(inorder.substr(pos + 1), postorder.substr(0, pos));
}
int main() {
const string in, post;
cin >> in >> post;
reconstructPreorder(in, post);
cout << endl;
return 0;
}
这里空空如也
有帮助,赞一个