本题要求给定二叉树的高度。
函数接口定义:
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;
}
/* 你的代码将被嵌在这里 */
答案:递归实现。(叶子节点的高度为1,空树高度为1)球一棵树的高度,如果分别求出左右儿子的高度,那我们取最大,再加1(加上根节点),就是整棵树的高度。
int GetHeight( BinTree BT )
{
int hl,hr,max;
if(BT)
{
hl=GetHeight(BT->Left);
hr=GetHeight(BT->Right);
max=hl>hr?hl:hr;
return (max+1);
}
else return 0;
}