7-23 还原二叉树 (25 分)

7-23 还原二叉树 (25 分)

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

输入格式:

输入首先给出正整数$N$(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为$N$的不包含重复英文字母(区别大小写)的字符串。

输出格式:

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

输入样例:

1
2
3
9
ABDFGHIEC
FDHGIBEAC

输出样例:

1
5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct TNode
{
char data;
struct TNode *lchild,*rchild;
} TNode,*Tree;

Tree CreatTree( char xian[],char zhong[],int n);
int High( Tree t);

char xian[55]; //先序序列
char zhong[55]; //中序序列
int n;

int main()
{
scanf("%d",&n);
scanf("%s",xian);
scanf("%s",zhong);
Tree tree = CreatTree( xian,zhong,n);
printf("%d",High(tree));
return 0;
}

Tree CreatTree( char xian[],char zhong[],int n)
{
if( n==0 ) return NULL;
int index = 0;
Tree temp = (Tree) malloc(sizeof(struct TNode));

while( index < n)
{
if( zhong[index]==xian[0]) break;
index ++;
}
temp->data = xian[0];
temp->lchild = CreatTree(xian+1,zhong,index);
temp->rchild = CreatTree(xian+1+index,zhong+index+1,n-index-1);
return temp;
}

int High( Tree t)
{
if( !t ) return 0;
int lh = High(t->lchild);
int rh = High(t->rchild);
if( lh>rh ) return ++lh;
else return ++rh;
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×