1. 程式人生 > >第六章樹和二叉樹作業1—二叉樹--計算機17級 6-1 求二叉樹高度 (20 分)

第六章樹和二叉樹作業1—二叉樹--計算機17級 6-1 求二叉樹高度 (20 分)

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 HL,HR,HMax;
    if(BT)
    {
        HL = GetHeight(BT->Left);//求左子樹深度
        HR = GetHeight(BT->Right);//求右子樹深度
        HMax = (HL > HR) ? HL : HR;
        return (HMax+1);//返回樹的深度
    }
    else
        return 0;
}

 完整實現程式碼(即把建立樹的程式碼也實現了)

#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(void)
{
	BinTree BT = CreatBinTree();
	printf("%d\n", GetHeight(BT));
 
	return 0;
}
BinTree CreatBinTree()
{//層序生成二叉樹
	//特殊限制,輸入為0的時候為葉節點
	BinTree BT;
	ElementType T;
	int front = 0, tail = 0;
	BinTree Queue[1001] = { '\0' };//父節點數列
	BinTree Date;
	scanf("%c", &T);
	if (T == '0')//空樹
		return NULL;
	else
	{
		BT = (BinTree)malloc(sizeof(struct TNode));
		if (BT == NULL)
			return NULL;
		BT->Data = T;//根節點賦值
		BT->Left = BT->Right = NULL;//初始化左右子樹
		Queue[tail++] = BT;
	}
	while (Queue[front]!=NULL) {//根節點入佇列
		Date = Queue[front++];
		scanf("%c", &T);
		if (T == '0')
			Date->Left = NULL;
		else
		{
			Date->Left = (BinTree)malloc(sizeof(struct TNode));
			if (Date->Left == NULL)//先完成左樹的操作,然後完成右樹的操作
				return NULL;
			Date->Left->Data = T;
			Date->Left->Left = Date->Left->Right = NULL;
			Queue[tail++] = Date->Left;
		}
		scanf("%c", &T);
		if (T == '0')
			Date->Right = NULL;
		else
		{
			Date->Right = (BinTree)malloc(sizeof(struct TNode));
			if (Date->Right == NULL)
				return NULL;
			Date->Right->Data = T;
			Date->Right->Left = Date->Right->Right = NULL;
			Queue[tail++] = Date->Right;
		}
	};
 
	return BT;
}
int GetHeight(BinTree BT)//遞迴方法
{
	int LH, RH;//對左右子樹的高度進行記錄
	if (!BT)//末位,遞迴停止
		return 0;
	else
	{
		LH = GetHeight(BT->Left);
		RH = GetHeight(BT->Right);
		return LH > RH ? ++LH : ++RH;//返回左右子樹中值最大的,再加上當前父節點,因為不會統計父節點
	}
}