PTA数据结构 6-1求二叉树高度
题目概述
本题要求给定二叉树的高度。## 参考代码
函数接口定义
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 L,R; //初始化二叉树左右两个分支的高度
if(BT==NULL) //判断是否空树,同时也是递归调用的终止条件
{
return 0;
}
else
{
L=GetHeight(BT->Left); //左子树的高度
R=GetHeight(BT->Right); //右子树的高度
if(L>=R) //返回高度高的子树+1
{
return L+1;
}
else
{
return R+1;
}
}
}