前序 + 中序
#include<iostream>
#include<deque>
using namespace std;
deque<int> rear,center,pref;
void build(deque<int> pre,deque<int> cen){
int temp;
if(pre.size()) temp = pre.front();
else return;
int pos;
for(int i = 0;i < cen.size();i ++){
if(cen[i] == pre.front()){
pos = i;
break;
}
}
pre.pop_front();
deque<int> p,c;
p.assign(pre.begin(),pre.begin() + pos);
c.assign(cen.begin(),cen.begin() + pos);
build(p,c);
p.clear(),c.clear();
p.assign(pre.begin() + pos,pre.end());
c.assign(cen.begin() + pos + 1,cen.end());
build(p,c);
rear.push_back(temp);
}
int main(){
int n;
cin >> n;
for(int i = 0;i < n * 2;i ++){
int t;
cin >> t;
if(i < n) center.push_back(t);
else pref.push_back(t);
}
build(pref,center);
for(auto i : rear) cout << i << ' ';
}
中序 + 后序
#include<iostream>
#include<vector>
using namespace std;
const int N = 50;
vector<int> rear;
vector<int> center;
vector<int> pre;
int n;
void build(vector<int> re,vector<int> cen){
if(re.size()) pre.push_back(re.back());
else return;
int pos;
for(int i = 0;i < cen.size();i ++){
if(cen[i] == re.back()){
pos = i;
break;
}
}
re.pop_back();
vector<int> r,c;
r.assign(re.begin(),re.begin() + pos);
c.assign(cen.begin(),cen.begin() + pos);
build(r,c);
r.clear(),c.clear();
r.assign(re.begin() + pos,re.end());
c.assign(cen.begin() + pos + 1,cen.end());
build(r,c);
}
int main(){
cin >> n;
for(int i = 0;i < n * 2;i ++){
int t;
cin >> t;
if(i < n) rear.push_back(t);
else center.push_back(t);
}
build(rear,center);
cout << "Preorder:";
for(auto i : pre) cout << ' ' << i;
}
cite