您的位置:首页 > 理论基础 > 数据结构算法

SDUT 3343 数据结构实验之二叉树四:(先序中序)还原二叉树

2017-11-08 19:38 549 查看

数据结构实验之二叉树四:(先序中序)还原二叉树

Time Limit: 1000MS
Memory Limit: 65536KB
Submit

Statistic
Discuss

Problem Description

给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。

Input

输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。

 

Output

 输出一个整数,即该二叉树的高度。

Example Input

9
ABDFGHIEC
FDHGIBEAC


Example Output

5


Hint

#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef struct node
{
char data;
struct node *l;
struct node *r;
}BTnode;
char pre[55],in[55];
BTnode *Create(char pre[],char in[],int n)
{
BTnode *root;
char *p;
int k;
if(n<=0) return NULL;
root=(BTnode *)malloc(sizeof(BTnode));
root->data=*pre;
for(p=in;p<in+n;p++)
if(*p==*pre)
break;
k=p-in;
root->l=Create(pre+1,in,k);
root->r=Create(pre+k+1,p+1,n-k-1);
return root;
}
int Gethigh(BTnode *root)
{
int n,m;
if(root==NULL)
return 0;
else
{
n=Gethigh(root->l);
m=Gethigh(root->r);
if(n>m)
return n+1;
else
return m+1;
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
scanf("%s",pre);
scanf("%s",in);
BTnode *root;
root=Create(pre,in,n);
printf("%d\n",Gethigh(root));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: