c语言假设二叉树采用二叉链表存储结构,设计一个非递归算法求二叉树的高度

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

  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值