Problem Description
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
Input
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
Output
输出一个整数,即该二叉树的高度。
Sample Input
9 ABDFGHIEC FDHGIBEAC
Sample Output
5
#include <stdio.h>
#include <stdlib.h>
struct node
{
char data;
struct node *lc;
struct node *rc;
};
struct node *creat(int n,char *a,char *b)
{
int i;
struct node *root;//注意结构体要定义在这
if(n==0) root=NULL;
else
{
root=(struct node *)malloc(sizeof(struct node));
root->data=a[0];
for(i=0;i<=n-1;i++)
{
if(b[i]==a[0])
break;
}
root->lc=creat(i,a+1,b);
root->rc=creat(n-i-1,a+i+1,b+i+1);
}
return root;
}
int deep(struct node *root)
{
int ld,rd;
if(root!=NULL)
{
ld=deep(root->lc);
rd=deep(root->rc);
if(ld>rd) return (ld+1);
else return (rd+1);
}
else return 0;
}
int main()
{
int n;
char a[51],b[51];
while(scanf("%d",&n)!=EOF)
{
struct node *root;
scanf("%s",a);
scanf("%s",b);
root=creat(n,a,b);
printf("%d\n",deep(root));
}
return 0;
}