数据结构--还原二叉树

来源:互联网 发布:网络基础知识教程 编辑:程序博客网 时间:2024/05/18 01:45

数据结构实验之二叉树四:还原二叉树

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

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

Input

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

Output

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

Example Input

9 ABDFGHIECFDHGIBEAC

Example Output

5
#include<stdio.h>
#include<string.h>
#include<malloc.h>
struct node 
{
char data;
struct node *l,*r;
};
struct node *creat(char *pre,char *in,int len)
{
struct node *root;
if(len<=0)
return NULL;
else
{
root=(struct node *)malloc(sizeof(struct node));
root->data=*pre;
char *p;
for(p=in;p!=NULL;p++)
{
if(*p==*pre)
{
break;
}
}
int lon=p-in;
root->l=creat(pre+1,in,lon);
root->r=creat(pre+lon+1,p+1,len-lon-1);
}
return root;
}
int deep(struct node *root)
{
if(!root)
return 0;
int i,j;
i=deep(root->l);
j=deep(root->r);
if(i>j)
return i+1;
else return j+1;
}
int main()
{
int n;
struct node *root;
char a[55],b[55];
while(scanf("%d",&n)!=EOF)
{
scanf("%s",a);
scanf("%s",b);
char *pre,*in;
pre=a;
in=b;
root=creat(pre,in,n);
printf("%d\n",deep(root));
}
return 0;
}
0 0