problem
This problem requires a binary tree of a given height.
Function interface definition:
int GetHeight (Bintree BT);
Wherein BinTree structure is defined as follows:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
Required function returns the value of a given height of the binary tree BT.
Referee test program Example:
#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 (); / * implementation details ignored * /
int GetHeight (BinTree BT);
int main()
{
BinTree BT = CreatBinTree();
printf("%d\n", GetHeight(BT));
return 0;
}
Solution
int GetHeight( BinTree BT )
{
int HL, HR, MaxH;
if (BT)
{
HL = GetHeight(BT->Left);
HR = GetHeight(BT->Right);
MaxH = HL > HR ? HL : HR;
return MaxH + 1;
}
else return 0;
}