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

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

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

函数接口定义:

int GetHeight( BinTree BT );

其中BinTree结构定义如下:

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

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

裁判测试程序样例:

#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;
}
/* 你的代码将被嵌在这里 */

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

4

 

程序代码:

 1 //
 2 //  main.cpp
 3 //  4-8 求二叉树高度 
 4 #include<iostream>
 5 #include<stdio.h>
 6 #include<stdlib.h>
 7 #include<string.h>
 8 using namespace std;
 9 #define OVERFLOW -2
10 typedef char ElementType;
11 typedef struct TNode *Position;
12 typedef Position BinTree;
13 struct TNode{
14     ElementType Data;
15     BinTree Left;
16     BinTree Right;
17 };
18 
19 BinTree CreatBinTree(){
20     BinTree BT = (BinTree)malloc(sizeof(struct TNode));
21     BT->Left=NULL;
22     BT->Right=NULL;
23     return BT;
24 }
25 int GetHeight( BinTree BT );
26 
27 int main()
28 {
29     BinTree BT = CreatBinTree();
30     printf("%d\n", GetHeight(BT));
31     return 0;
32 }

 

 1 /* 你的代码将被嵌在这里 */
 2 int GetHeight(BinTree BT)//输出二叉树的高度
 3 {
 4     int high=0;int high1,high2;
 5     if(BT)
 6     {
 7         high1=GetHeight(BT->Left);
 8         high2=GetHeight(BT->Right);
 9         if(high1>high2)
10             high=high1;
11         else
12             high=high2;
13     }
14     return high;
15 }

 

posted @ 2017-02-04 09:56  女王公园的八神  阅读(1383)  评论(1编辑  收藏  举报