给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
#include<bits/stdc++.h>
using namespace std;
struct node{
char data;
node *l;
node *r;
};
int n,h;
char xian[55],zhong[55];
node *huanyuan(char *xian,char *zhong,int k)
{
node *head;
if(k==0)
return NULL;
head=(struct node *)malloc(sizeof(struct node));
int tmp=xian[0];
head->data=xian[0];
int idx;
for(int i=0;i<k;i++)
{
if(zhong[i]==tmp)
{
idx=i;
break;
}
}
head->l=huanyuan(xian+1,zhong,idx);
head->r=huanyuan(xian+1+idx,zhong+idx+1,k-idx-1);
return head;
}
//void show(node *root)
//{
// if(root==NULL)
// return;
// cout<<root->data;
// if(root->l)
// show(root->l);
// if(root->r)
// show(root->r);
//}
int deep(node *T)
{
if(T==NULL)
return 0;
int hr=deep(T->l);
int hl=deep(T->r);
h=(hr>hl?hr:hl)+1;
return h;
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
cin>>xian[i];
for(int i=0;i<n;i++)
cin>>zhong[i];
node *T=huanyuan(xian,zhong,n);
h=deep(T);
cout<<h;
return 0;
}