数据结构实验--还原二叉树

一、问题描述

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

 

二、输入/输出

输入说明:输入正整数N,为树中结点总数。另外给出先序遍历序列和中序遍历序列。

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

 

三、代码
 
 1 # include <stdio.h>
 2 # include <malloc.h>
 3 
 4 typedef struct tagNode
 5 {
 6     char data;
 7     struct tagNode *left;//左孩子
 8     struct tagNode *right;//右孩子
 9 }BitTree;
10 
11 BitTree * PreIn(char *pre, char *in, int n)
12 {
13 
14     int i = 0;
15     BitTree *BT = NULL;
16     BitTree *left = NULL;
17     BitTree *right = NULL;
18     if(n == 0) return NULL;
19 
20     BT = (BitTree*)malloc(sizeof(BitTree));
21     BT->data = pre[0];
22 
23     for(i = 0; i < n; i++)
24     {
25         if(pre[0] == in[i])
26             break;
27     }
28 
29     left = PreIn(pre+1, in, i);
30     right = PreIn(pre+i+1, in+i+1, n-i-1);
31 
32     BT->left = left;
33     BT->right = right;
34 
35     return BT;
36 }
37 
38 int GetBitTreeHight(BitTree *BT)
39 {
40     int HL, HR, MaxH;
41     if(BT)
42     {
43         HL = GetBitTreeHight(BT->left);
44         HR = GetBitTreeHight(BT->right);
45 
46         MaxH = HL > HR?HL : HR;
47 
48         return MaxH + 1;
49     }
50 
51     else
52     {
53         return 0;
54     }
55 }
56 int main()
57 {
58     int size;
59     int h;
60     char pre[50];
61     char in[50];
62     BitTree * BT;
63     printf("请输入结点个数:");
64     scanf("%d",&size);
65     printf("\n请输入先序序列\n");
66     scanf("%s", pre);
67     printf("\n请输入中序序列\n");
68     scanf("%s", in);
69 
70     BT = PreIn(pre, in, size);
71 
72     h = GetBitTreeHight(BT);
73     printf("二叉树高度为%d", h);
74     return 0;
75 
76 
77 }
View Code

参考:http://blog.csdn.net/cwqbuptcwqbupt/article/details/6874622

posted @ 2013-10-30 21:31  艾斯泽  阅读(1085)  评论(0编辑  收藏  举报