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 LD = 0, RD = 0;
if(BT == NULL)
return 0;
else{
LD = GetHeight(BT -> Left);
RD = GetHeight(BT -> Right);
return LD > RD ? (LD + 1):(RD + 1);
}
}
测试点
引用块内容测试点 提示 结果 耗时 内存
0 同sample,最后一层有单左和单右孩子,有左高、右高、等高判断 答案正确 2 ms 164KB
1 喇叭树,两个单边,右高 答案正确 2 ms 136KB
2 喇叭树,两个单边,左高 答案正确 1 ms 256KB
3 只有1个结点 答案正确 2 ms 164KB
4 空树 答案正确 2 ms 256KB