这道题也是二叉树遍历的入门题
建议结合PATA1020学习
这道题涉及先序遍历和中序遍历还原树,同时计算树的高度。

#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=258;
int n;
int pre[maxn];
int in[maxn];
struct node{
	int data;
	node* lchild;
	node* rchild;
};
node* create(int preL,int preR,int inL,int inR){
	if(preL > preR) return NULL;
	node* root = new node;
	root->data = pre[preL];
	int k=inL;
	while(k<=inR && in[k] != pre[preL]){
		k++;
	}
	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 height(node* root){
	if(root == NULL) return 0;
	return 1 + max(height(root->lchild), height(root->rchild));
}
int main(){
	scanf("%d",&n);
	char c;
	getchar();
	for(int i=0;i<n;i++){
		scanf("%c",&c);
		pre[i]=c-0;
	}
	getchar();
	for(int i=0;i<n;i++){
		scanf("%c",&c);
		in[i]=c-0;
	}
	node* root = create(0,n-1,0,n-1);
	int ans=height(root);
	printf("%d\n",ans);

	return 0;
}