题目描述
函数接口定义:
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;
}
/* 你的代码将被嵌在这里 */
解题思路
很基本的利用递归的思想求二叉树的高度,相关思路已写在代码内部
C语言解法
int GetHeight( BinTree BT )
{
// 利用递归的思想求二叉树高度
int leftH=0,rightH=0; // 由于是二叉树 定义左右递归高度
// 递归出口 如果指针BT为NULL说明无这个节点,节点已不在树中
if(BT==NULL)
{
return 0; // 返回0表示假代表结束
}
leftH=GetHeight(BT->Left)+1; // 递归求左边的最大高度
rightH=GetHeight(BT->Right)+1; // 递归求右边的最大高度
// 通过判断返回左右两边最大的边的高度
return leftH>rightH? leftH:rightH;
/*
这段return等效于
if(leftH>rightH)
{
return leftH;
}
else
{
return rightH;
}
*/
}