c语言二叉树高度两种计算方式


思路:采用层次遍历,设置一个变量last记录当前层最右结点的下标,每次循环与last比较,相等,则层数+1,并且让last指向下一层最右结点下标,直到退出循环,level即为高度
样例:
在这里插入图片描述

一、非递归方法

//二叉树结构体
typedef struct bitree {
	char data;
	struct bitree* lchild, * rchild;
}bitree;
//队列
typedef struct {
	bitree* data[50];
	int front, rear;
}sequeue;
//二叉树的创建
bitree* create(bitree* t) {
	char ch;
	scanf("%c", &ch);
	if (ch =='#') {
		return NULL;
	}
	else {
		t = (bitree*)malloc(sizeof(bitree));
		t->data = ch;
		t->lchild = create(t->lchild);
		t->rchild = create(t->rchild);
		return t;
	}
}
//计算二叉树的深度
int Btdepth(bitree* t) {
	if (t == NULL) {
		return 0;
	}
	int last = 0, level = 0;//last 指向最右层的结点,level记录高度
	sequeue s;
	s.front = s.rear = 0;  //队列初始化
	bitree* p = t;
	s.data[(s.rear)++] = p; //根节点入队
	while (s.front != s.rear) {     
		p = s.data[(s.front)++];
		if (p->lchild != NULL) {
			s.data[(s.rear)++] = p->lchild;
		}
		if (p->rchild != NULL) {
			s.data[(s.rear)++] = p->rchild;
		}
		if (last == s.front - 1) {  //这里减一是因为,front是在赋值结束之后会才会自增,所以-1
			level++;
			last = s.rear - 1;   //last记录下一层的最后一个结点的下标
		}
		 
	}
	return level;
}

int main() {
	bitree* t = NULL;
	t = create(t);
	int level = Btdepth(t);
	printf("该二叉树的高度:%d", level);
	return 0;
}

一、递归方法

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include <stdlib.h>

typedef struct bitree {
	char data;
	struct bitree* lchild, * rchild;
}bitree;

bitree* create(bitree* t) {
	char ch;
	scanf("%c", &ch);
	if (ch == '#') {
		return NULL;
	}
	else {
		t = (bitree*)malloc(sizeof(bitree));
		t->data = ch;
		t->lchild = create(t->lchild);
		t->rchild = create(t->rchild);
		return t;
	}
}

int Btdepth(bitree* t) {
	if (t == NULL) {
		return 0;
	}
	int ldep = Btdepth(t->lchild);
	int rdep = Btdepth(t->rchild);
	if (ldep > rdep)
		return ldep + 1;
	else
		return rdep + 1;

}

int main() {
	bitree* t = NULL;
	t = create(t);
	int level = Btdepth(t);
	printf("二叉树的高度为:%d", level);
	return 0;
}

结果:
在这里插入图片描述

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值