题目链接
根据二叉树的前序遍历和中序遍历还原树,并输出后序遍历。

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+5;
char pre[maxn],in[maxn];
struct node{
	node* left, *right;
	char val;
};
node* create(int preL, int preR, int inL, int inR){
	if(preL > preR) return nullptr;
	node* root = new node;
	root->val = pre[preL];
	int k = inL;
	while(in[k] != pre[preL]){
		k++;
	}
	int left = k - inL;
	root->left = create(preL+1, preL+left,inL, k-1);
	root->right = create(preL+left+1, preR, k+1, inR);
	return root;
}
void inorder(node* root){
	if(root==nullptr) return;
	inorder(root->left);
	inorder(root->right);
	cout<<root->val;
}
int main(){
	while(cin>>pre>>in){
		int len = strlen(pre);
		node* root = create(0, len-1, 0, len-1);
		inorder(root);	
		cout<<endl;
	}
	return 0;
}