H - 数据结构实验之二叉树四:(先序中序)还原二叉树
Description
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
Input
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
Output
输出一个整数,即该二叉树的高度。
Sample
Input
9 ABDFGHIEC FDHGIBEAC
Output
5
#include<bits/stdc++.h>
using namespace std;
char a[101];
int i,num;
struct node{
char data;
struct node *l,*r;
};
node *creat(char *p,char *m,int len){
if(len<=0) return NULL;
node *root;
root=new node;
root->data=p[0];
int i;
for(i=0;i<len;i++){
if(m[i]==p[0]) break;
}
root->l=creat(p+1,m,i);
root->r=creat(p+i+1,m+i+1,len-1-i);
return root;
}
int height(node *root){
int h=0;
if(root){
h=max(height(root->l),height(root->r))+1;
}
return h;
}
int main()
{
int n;
char p[105],m[105];
while(cin>>n){
cin>>p>>m;
node *root;
root=creat(p,m,n);
int ans=height(root);
cout<<ans<<endl;
}
return 0;
}