数据结构----二叉树叶子结点到根节点的高度计算

数据结构----二叉树叶子结点到根节点的高度计算

代码:

#include<stdio.h>
#include<stdlib.h>
typedef struct bstTree {
	int data;
	struct bstTree* lchild, *rchild;
}bstTree;
void createBSTTree(bstTree* & T, int data) {//创建二叉排序树
	bstTree *p = NULL;
	if (!T) {
		p = (bstTree*)malloc(sizeof(bstTree));
		p->data = data;
		p->lchild = p->rchild = NULL;
		T = p;
		return;
	}
	if (data < T->data) {//左子树插入
		createBSTTree(T->lchild, data);
	}
	else {//右子树插入
		createBSTTree(T->rchild, data);
	}
}
void prePrint(bstTree*  BSTTree) {//前序遍历二叉排序树
	if (BSTTree) {
		printf("%d ", BSTTree->data);
		prePrint(BSTTree->lchild);
		prePrint(BSTTree->rchild);
	}
}
void calLeafHeight(bstTree* T,int h) {//计算叶子结点到根节点的高度
	if (!T) {
		return;
	}
	if (T->lchild == NULL && T->rchild == NULL) {
		printf("%d叶子结点到根节点的高度为%d\n", T->data, h + 1);
	}
	else {
		calLeafHeight(T->lchild, h + 1);//左孩子
		calLeafHeight(T->rchild, h + 1);//右孩子
	}
}
int main() {
	bstTree* T = NULL;//一定要初始化为空树
	int count, data;
	printf("开始构造二叉排序树:\n输入二叉排序树结点的数目:");
	scanf_s("%d", &count);
	while (count--) {//构造二叉排序树
		printf("输入二叉排序树的第%d个结点:", count + 1);
		scanf_s("%d", &data);
		createBSTTree(T, data);
	}
	printf("前序遍历二叉排序树\n");
	prePrint(T);//前序遍历二叉排序树
	printf("\n");
	calLeafHeight(T, 0);
	printf("\n");
	system("pause");
	return 0;
}

测试截图:

请添加图片描述

时间复杂度O(logn),空间复杂度O(1)

如果存在什么问题,欢迎批评指正!谢谢!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fighting的码农(zg)-GPT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值