方法一:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
char pre[51],in[51];
int n;
int fun(int t,int low,int high){
if(low>=high)
return 1;
else {
int mid=0;
for(int i=low;i<=high;i++){
if(in[i]==pre[t]){
mid=i;
break;
}
}
int h1=fun(t+1,low,mid-1)+1; //前序序列的t+1号为当前节点的左孩子
int h2=fun(t+mid-low+1,mid+1,high)+1; //前序序列的t+mid-low+1号为当前节点的右孩子
return h1>h2?h1:h2;
}
}
int main(){
cin>>n;
cin>>pre>>in;
int h=fun(0,0,n-1);
cout<<h;
return 0;
}
方法二:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct TNode
{
char data;
struct TNode *lchild,*rchild;
} TNode,*Tree;
Tree CreatTree( char xian[],char zhong[],int n);
int High( Tree t);
char xian[55]; //先序序列
char zhong[55]; //中序序列
int n;
int main()
{
scanf("%d",&n);
scanf("%s",xian);
scanf("%s",zhong);
Tree tree = CreatTree( xian,zhong,n);
printf("%d",High(tree));
return 0;
}
Tree CreatTree( char xian[],char zhong[],int n)
{
if( n==0 ) return NULL;
int index = 0;
Tree temp = (Tree) malloc(sizeof(struct TNode));
while( index < n)
{
if( zhong[index]==xian[0]) break;
index ++;
}
temp->data = xian[0];
temp->lchild = CreatTree(xian+1,zhong,index);
temp->rchild = CreatTree(xian+1+index,zhong+index+1,n-index-1);
return temp;
}
int High( Tree t)
{
if( !t ) return 0;
int lh = High(t->lchild);
int rh = High(t->rchild);
if( lh>rh ) return ++lh;
else return ++rh;
}