Problem Description
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
Input
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
Output
输出一个整数,即该二叉树的高度。
Sample Input
9 ABDFGHIEC FDHGIBEAC
Sample Output
5
#include <bits/stdc++.h>
using namespace std;
typedef struct tnode{
char data;
struct tnode *lc,*rc;
}tnode,*tree;
tree create(char pre[],char inorder[],int n)
{
int i;
tree t;
if(n==0) return NULL;
for(i=0;i<n;i++){
if(pre[0]==inorder[i])
break;
}
t=new(tnode);
t->data=pre[0];
t->lc=create(pre+1,inorder,i);
t->rc=create(pre+1+i,inorder+1+i,n-1-i);
return t;
}
int depth(tree t)
{
int d,l,r;
if(!t) d=0;
else{
l=depth(t->lc);
r=depth(t->rc);
d=1+(l>r?l:r);
}
return d;
}
int main()
{
int n;
char a1[55],a2[55];
while(cin>>n){
cin>>a1>>a2;
tree t;
t=create(a1,a2,n);
cout<<depth(t)<<endl;
}
return 0;
}