数据结构例26.求二叉树的高度

这篇博客介绍了如何使用C++编程实现求解二叉树高度和指定节点层次的算法。通过先序遍历的方式创建二叉树,并利用递归计算树的高度。在给定的代码中,`height` 函数计算了树的最大深度,而`createbitree`函数用于从用户输入构建二叉树。
摘要由CSDN通过智能技术生成

*/
假设二叉树采用二叉链表存储结构,试设计一个算法
求二叉树的高度并给出指定结点的所在的层数(高度)
*/

# include <iostream>
# include <stdlib.h>
# include <stdio.h>
using namespace std;

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

void createbitree(bitree &t)
{
	char ch;
	ch = getchar();

	if(ch == ' ')
		t = NULL;

	else
	{
		t = (bitree) malloc(sizeof(bitree));
		t->data = ch;
		createbitree(t->lchild);
		createbitree(t->rchild);
	}
}

int height(bitree t)
{
	int a, b, max;

	if(t)
	{
		a = height(t->lchild);
		b = height(t->rchild);
		max = a>b ? a : b;
		return (max+1);
	}

	else
		return 0;
}

int main()
{
	bitree t;
	printf("请输入以先序建树的字母序列:\n");
	createbitree(t);
	printf("树的高度为:%d", height(t));
	printf("\n");

	return 0;
}

**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值