查看原题目请点我这里
解题思路
首先利用前序和中序还原二叉树,然后利用后序遍历输出。
这就是模板。
注意
因为输入的是字母,所以树的结构体中应该改为char。
可以先把中序中字符对应的下标存起来,这样可以适当加速。
版本2
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstdio>
#include <cctype>
#include <unordered_map>
#include <map>
using namespace std;
const int N = 105;
typedef pair<int, string> PII;
unordered_map<char, int> mp;
string a, b;
struct tree{
char val;
tree* left, * right;
tree(char x){
val = x;
left = right = nullptr;
}
};
//建树
tree* create(int pl, int pr, int inl, int inr){
if(pl > pr) return nullptr;
tree* root = new tree(a[pl]);
int k = mp[a[pl]];
int left = k - inl;
root->left = create(pl+1, pl+left, inl, k-1);
root->right = create(pl+left+1, pr, k+1, inr);
return root;
}
//后序
void postorder(tree* root){
if(!root) return;
postorder(root->left);
postorder(root->right);
cout<<root->val;
}
int main() {
while(cin>>a>>b){
mp.clear();
for(int i = 0; i < b.size(); i++){
mp[b[i]] = i;
}
tree* root = create(0, a.size()-1, 0, b.size()-1);
postorder(root);
cout<<endl;
}
return 0;
}
版本1
//由前序遍历和中序遍历还原后序遍历
#include <cstdio>
#include <cstring>
char str1[30],str2[30];
struct node { //创建结构体
char data;
node* lchild;
node* rchild;
};
void postorder(node* root){
if(root->lchild != NULL) {
postorder(root->lchild);
}
if(root->rchild != NULL) {
postorder(root->rchild);
}
printf("%c",root->data);
}
node* create(int preL,int preR, int inL, int inR){
if(preL > preR) {
return NULL; //叶子节点设为NULL
}
node* root = new node; //创建新节点
root->data = str1[preL];
int k;
for(k = inL;k <= inR;k++){ //找到中序中根的位置
if(str2[k] == root->data) {
break;
}
}
int numLeft = k - inL; //对左右树进行递归建树
root->lchild = create(preL + 1,preL + numLeft, inL,k - 1);
root->rchild = create(preL + numLeft + 1, preR, k + 1,inR);
return root;
}
int main() {
while(scanf("%s%s",str1,str2)!=EOF) {
int len1 = strlen(str1);
int len2 = strlen(str2);
node* root = create(0,len1-1,0,len2-1); //还原树
postorder(root);
}
return 0;
}