1.递归法
/***
递归思想:max(left,right)+1
**/
int GetHeight(BinTree BT){
//走到尽头
if(!BT)
return 0;
int left = GetHeight(BT->Left);
int right = GetHeight(BT->Right);
return (left>right?left:right)+1;
}
2.层次遍历思想
/**
层次遍历思想
**/
int GetHeight(BinTree BT){
if(!BT)
return 0;
//队列,简化起见这里没有应用循环队列
BinTree q[1000];
int front = 0;
int rear = 1;
//根结点入队
q[0] = BT;
//计数变量用于判断本层是否遍历完
//已经遍历结点个数
int count = 0;
//下层结点总数,初始为根节点1
int nextCount = 1;
//工作指针
BinTree temp;
//高度
int height = 0;
//队列不为空
while(front<rear){
//计数
count++;
//出队
temp = q[front++];
//左右孩子入队
if(temp->Left)
q[rear++] = temp->Left;
if(temp->Right)
q[rear++] = temp->Right;
//判断本层结点是否遍历完
if(count>=nextCount){
//高度累加
height++;
//计数器清零
count=0;
//计算下层结点数量
nextCount = rear-front;
}
}
return height;
}