Description
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
Input
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
Output
输出一个整数,即该二叉树的高度。
Sample
Input
9
ABDFGHIEC
FDHGIBEAC
Output
5
#include<bits/stdc++.h>
struct node
{
char ch;
struct node *lchild,*rchild;
};
struct node *creatTree(int n,char s1[],char s2[])
{
struct node *t;
int i=0;
if (n==0)
{
return NULL;
}
//建树
//malloc 向系统申请分配指定size个字节的内存空间
t=(struct node *)malloc(sizeof(struct node));
//取前序的第一个元素
t->ch=s1[0];
for (i=0;i<n;i++)
{
if (s1[0]==s2[i]) //寻找中序中的那个元素位置
{
t->lchild=creatTree(i,s1+1,s2);
t->rchild=creatTree(n-i-1,s1+i+1,s2+i+1);
}
}
return t;
}
int depth(struct node *t)
{
int n,m;
if (t==NULL)
{
return 0;
}else
{
m=depth(t->lchild);
n=depth(t->rchild);
if (m>n)
{
return (m+1);
}else return (n+1);
}
}
int main()
{
int n;struct node *t;
char s1[50],s2[50];
while (~scanf("%d\n%s\n%s",&n,s1,s2))
{
t=creatTree(n,s1,s2);
printf("%d\n",depth(t));
}
return 0;
}