1. 程式人生 > >資料結構二叉樹的深度

資料結構二叉樹的深度

6-8 求二叉樹高度 (20 point(s))

本題要求給定二叉樹的高度。

函式介面定義:

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;
}
/* 你的程式碼將被嵌在這裡 */

 

這是一個典型的遞迴演算法

int GetHeight(BinTree BT)
{
	
	if (BT == NULL)
		return 0;

	int heightL = GetHeight(BT->Left);
	int heightR = GetHeight(BT->Right);
	return (heightL > heightR ? heightL : heightR) + 1;
	 

}