本题要求给定二叉树的高度。
函数接口定义:
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
8分的代码:
int GetHeight( BinTree BT )
{
BinTree queue[1005];
int front , rear;
if(BT==NULL)return 0;
front=-1;rear=0;
queue[rear]=BT;
int num=0;
//队列遍历
while(front!=rear)//队列非空
{
front++;//出队列
num++;
if(queue[front]->Left)//存在左子树
{
rear++;
queue[rear]=queue[front]->Left;
}
if(queue[front]->Right)//存在右子树
{
rear++;
queue[rear]=queue[front]->Right;
}
}
int x=log(num)*1.0/log(2);
return x+1;
}
错误原因:
这种方法是通过队列遍历获得节点个数,然后返回 log(n)/log(2)+1 的值,但是这种方法是求完全二叉树深度的,喇叭树必然不会是完全二叉树,所以错误。
正确代码:
int GetHeight( BinTree BT )
{
if(!BT)return 0;
return GetHeight(BT->Left)>GetHeight(BT->Right)?GetHeight(BT->Left)+1:GetHeight(BT->Right)+1;
}
587





