7-1 还原二叉树 (25 分)
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
结尾无空行
输出样例:
5
结尾无空行
#include <stdio.h>
#include <stdlib.h>
typedef struct TNode{
char data;
struct TNode *Ichild,*rchild;
}*Tree;
Tree CreatTree(char xian[] ,char zhong[],int n){
if(n==0)return NULL;
int index=0;
Tree temp =(struct TNode *)malloc(sizeof(struct TNode));
while(index<n){//找到根节点在中序的哪个位置
if(zhong[index]==xian[0])break;
index++;
}
temp->data=xian[0];//xian是移动的,xian[0]依次后移
temp->Ichild=CreatTree(xian+1,zhong ,index );//xian后羿一位,长度为index
temp->rchild=CreatTree(xian+1+index,zhong+1+index ,n-index-1 );//xian指向根节点后一位,长度为index
return temp;
}
int High(Tree t){
int h1=0,h2=0;
if(t==NULL)return 0;//从底部开始,向上递归,返回值为1
h1=High(t->Ichild);
h2=High(t->rchild);
if(h1>h2)return h1+1;//加一是根节点
else return h2+1;
}
int n;
char xian[55];
char zhong[55];
int main()
{
scanf("%d",&n);
scanf("%s",xian);
scanf("%s",zhong);
Tree tree=CreatTree(xian,zhong,n);
printf("%d",High(tree));
return 0;
}