chap 6 函數題6-1 求二叉樹高度 (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

 代碼:

int GetHeight( BinTree BT )
{
    int n,m;
    if(BT==NULL)
    {
        return 0;
    }
    else
    {
        m=GetHeight(BT->Left);
        n=GetHeight(BT->Right);
        if(m>n)
            return m+1;
        else
            return n+1;
    }
    
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章