1.若没有根结点,则直接返回高度为0
2.定义height,Maxheight,rear,front四个变量;创建一个指针数组代表队列,首先根结点进队;
3.如果队列非空将一直执行以下代码:
(1)将当前高度的结点出队,个数用rear-front表示
(2)高度+1
(3)并检测当前高度的所有结点的左右孩子,若非空则进队列
(4)判断当前高度与最大的高度的大小
#include <stdio.h>
#include <stdlib.h>
// 二叉树节点结构体
typedef struct Node {
int data;
struct Node *lchild;
struct Node *rchild;
} Node;
// 计算二叉树高度的非递归函数
int getHeight(Node *root) {
if(!root){
return 0;
}
int height=0,Maxheight=0;
int rear=0,front=0;
Node *queue[100];
queue[rear++]=root;
while(rear!=front){
int length=rear-front;
height+=1;
int i;
for(i=0;i<length;i++){
root=queue[front++];
if(root->lchild!=NULL){
queue[rear++]=root->lchild;
}
if(root->rchild!=NULL){
queue[rear++]=root->rchild;
}
}
if(height>Maxheight){
Maxheight=height;
}
}
return Maxheight;
}
int main() {
Node *p=(Node *)malloc(sizeof(Node));
p->data=1;
p->lchild=NULL;
p->rchild=NULL;
Node *m=(Node *)malloc(sizeof(Node));
m->data=2;
m->lchild=NULL;
m->rchild=NULL;
p->lchild=m;
Node *n=(Node *)malloc(sizeof(Node));
n->data=3;
n->lchild=NULL;
n->rchild=NULL;
p->rchild=n;
Node *a=(Node *)malloc(sizeof(Node));
a->data=4;
a->lchild=NULL;
a->rchild=NULL;
n->rchild=a;
int height = getHeight(p);
printf("二叉树高度: %d", height);
return 0;
}
得出结果:二叉树高度:3