非递归方式实现二叉树高度求解有点类似于二叉树的层序遍历,将二叉树存储的数据存入数组中,在计算时由上一层得到下一层的节点数量然后在遍历数组时读完相对应的数据量时高度累加
#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;
}
/* 你的代码将被嵌在这里 */
int GetHeight( BinTree BT ){//递归实现
if(BT==NULL)return 0;
int x=GetHeight(BT->Left);
int y=GetHeight(BT->Right);
if(x>y)return x+1;
else return y+1;
}
int GetHeight( BinTree BT ){//非递归实现
if(BT==NULL)return 0;
BinTree que[1000];//用数组模拟队列的使用(C里面没有stl)其实就是模拟其先进先使用的功能
//将树形结构的内容用数组的形式存下来
int tot=1;//记录该层一共有多少节点,刚开始只有一个根节点所以为1
int cnt=0;//记录在本层已经访问了多少节点
int p=0;//目前访问的节点总数
int pre=0;//模拟父亲节点
int res=0;//记录高度
que[p++]=BT;//放进队列
while(p>pre){//当p==pre时所有节点都处理结束
cnt++;
if(que[pre]->Left!=NULL){
que[p++]=que[pre]->Left;
}
if(que[pre]->Right!=NULL){
que[p++]=que[pre]->Right;
}
pre++;//更新父亲节点
if(cnt==tot){//这一层的节点全部访问结束
res++;
tot=p-pre;
cnt=0;
}
}
return res;
}