AcWing 3598. 二叉树遍历
原题链接
简单
作者:
CharlesLC
,
2021-07-19 10:01:16
,
所有人可见
,
阅读 548
#include <iostream>
#include <unordered_map>
using namespace std;
const int N = 50;
unordered_map<char, int> pos;
unordered_map<char, char> l, r;
string s1, s2;
//通过前序和中序构造树
char build(int il, int ir, int pl, int pr){
char root = s1[il];
int k = pos[root];
if(k > pl) l[root] = build(il + 1, k - 1 - pl + il + 1 , pl , k - 1);
if(pr > k) r[root] = build(k - 1 - pl + il + 2, ir, k + 1, pr);
return root;
}
//后序遍历
void visit(char root){
if(root){
visit(l[root]);
visit(r[root]);
cout << root;
}
}
int main(){
while(cin >> s1 >> s2){
int n = s1.size();
for(int i = 0; i < n; i ++) pos[s2[i]] = i;
char root = build(0, n - 1, 0, n - 1);
visit(root);
l.clear(), r.clear(); //清除哈希表,为下一次准备
cout << endl;
}
}