6-8 求二叉樹高度 (20分)
阿新 • • 發佈:2020-12-14
技術標籤:PTA:資料結構與演算法題目集(中文)# 函式題資料結構二叉樹演算法
資料結構與演算法題目集(中文)
6-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
AC程式碼:
int GetHeight(BinTree BT)
{
if (BT == NULL)
return 0;
int LH, RH;
LH = GetHeight(BT->Left);
RH = GetHeight(BT->Right);
return (LH > RH ? LH : RH) + 1;
}