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

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

输入格式:

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

输出格式:

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

输入样例:

9
ABDFGHIEC
FDHGIBEAC

输出样例:

5
解题思路:先序中第一个字母A为根节点,因而中序的第一个字母到A为A的左子树,A以后的字母为A的右子树,递归可建二叉树
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 
 5 typedef struct TNode
 6 {
 7     char data;
 8     struct TNode *lchild,*rchild;
 9 } TNode,*Tree;
10 
11 Tree CreatTree( char xian[],char zhong[],int n);
12 int High( Tree t);
13 
14 char xian[55];   //先序序列
15 char zhong[55];  //中序序列
16 int n;
17 
18 int main()
19 {
20     scanf("%d",&n);
21     scanf("%s",xian);
22     scanf("%s",zhong);
23     Tree tree = CreatTree( xian,zhong,n);
24     printf("%d",High(tree));
25     return 0;
26 }
27 
28 Tree CreatTree( char xian[],char zhong[],int n)
29 {
30     if( n==0 ) return NULL;
31     int index = 0;
32     Tree temp = (Tree) malloc(sizeof(struct TNode));
33 
34     while( index < n)
35     {
36         if( zhong[index]==xian[0]) break;
37         index ++;
38     }
39     temp->data = xian[0];
40     temp->lchild = CreatTree(xian+1,zhong,index);
41     temp->rchild = CreatTree(xian+1+index,zhong+index+1,n-index-1);
42     return temp;
43 }
44 
45 int High( Tree t)
46 {
47     if( !t ) return 0;
48     int lh = High(t->lchild);
49     int rh = High(t->rchild);
50     if( lh>rh ) return ++lh;
51     else return ++rh;
52 }

 






posted @ 2018-02-02 19:49  yuxiaoba  阅读(1257)  评论(0编辑  收藏  举报