给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
#include<stdio.h>
#include<stdlib.h>
#define Max 50
typedef struct Tree *BinTree;
struct Tree{
char data;
BinTree lchild;
BinTree rchild;
};
BinTree reCreate(char pre[],char in[],int len){
BinTree t;
int i = 0;
if(!len) return NULL;
else{
t = (BinTree)malloc(sizeof(struct Tree));
t->data = pre[0];
for(i;i<len;i++){
if(in[i]==pre[0]) break;
}
t->lchild = reCreate(pre+1,in,i);
t->rchild = reCreate(pre+i+1,in+i+1,len-i-1);
}
return t;
}
int getHigh(BinTree t){
int n = 0,m = 0;
if(!t) return 0;
n = getHigh(t->lchild);
m = getHigh(t->rchild);
return n>m?n+1:m+1;
}
int main(){
int n,h;
BinTree T;
char pre[Max+1],in[Max+1];
scanf("%d",&n);
getchar();
gets(pre);
gets(in);
T = reCreate(pre,in,n);
h=getHigh(T);
printf("%d",h);
return 0;
}