6-8 求二叉树高度 (20 分)

6-8 求二叉树高度 (20 分)

本题要求给定二叉树的高度。

函数接口定义:

1
int GetHeight( BinTree BT );

其中BinTree结构定义如下:

1
2
3
4
5
6
7
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};

要求函数返回给定二叉树BT的高度值。

裁判测试程序样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};

BinTree CreatBinTree(); /* 实现细节忽略 */
int GetHeight( BinTree BT );

int main()
{
BinTree BT = CreatBinTree();
printf("%d\n", GetHeight(BT));
return 0;
}
/* 你的代码将被嵌在这里 */

输出样例(对于图中给出的树):

1
4
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

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define OVERFLOW -2
typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};

BinTree CreatBinTree(){
BinTree BT = (BinTree)malloc(sizeof(struct TNode));
BT->Left=NULL;
BT->Right=NULL;
return BT;
}
int GetHeight( BinTree BT );

int main()
{
BinTree BT = CreatBinTree();
printf("%d\n", GetHeight(BT));
return 0;
}

/* 你的代码将被嵌在这里 */
int GetHeight(BinTree BT)//输出二叉树的高度
{
int high=4;int high1,high2;
if(BT)
{
high1=GetHeight(BT->Left);
high2=GetHeight(BT->Right);
if(high1>high2)
high=high1;
else
high=high2;
}
return high;
}
Your browser is out-of-date!

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

×