计算二叉树高度

1.递归

#include<iostream>
using namespace std;
#define MAX 15

typedef struct treenode
{
	char data;
	struct treenode* lchild, * rchild;
}BiTNode,*BiTree;
void build___tree(BiTree& t)
{
	char ch = getchar();
	if (ch == '#')
		t = NULL;
	else
	{
		t = (BiTree)malloc(sizeof(BiTNode));
		t->data = ch;
		t->lchild = NULL;
		t->rchild = NULL;
		build___tree(t->lchild);
		build___tree(t->rchild);
	}
}
void _print(BiTree t)
{
	if (t)
	{
		cout << t->data << " ";
		_print(t->lchild);
		_print(t->rchild);
	}
}
int _depth(BiTree t)
{
	if (!t)
		return 0;
	int left_depth = _depth(t->lchild);
	int right_depth = _depth(t->rchild);
	return fmax(left_depth, right_depth) + 1;
}
int main()
{
	BiTree t;
	build___tree(t);
	cout << "前序:" << endl;
	_print(t);
	cout << endl;
	cout << "树高:" << _depth(t);
}

2.非递归–辅助队–结点指针 max(层)=高度
每一层遍历到最右边+1

#include<iostream>
using namespace std;
#define MAX 15
typedef struct treenode
{
	char data;
	struct treenode* lchild, * rchild;
}BiNode,*BiTree;

void build__Tree(BiTree& t)
{
	char data;
	data = getchar();
	if (data == '#')
		t = NULL;
	else
	{
		t = (treenode*)malloc(sizeof(treenode));
		t->data = data;
		t->lchild = NULL;
		t->rchild = NULL;
		build__Tree(t->lchild);
		build__Tree(t->rchild);
	}
}
void print(BiTree t)
{
	if (t)
	{
		cout << t->data << " ";
		print(t->lchild);
		print(t->rchild);
	}
}
int depth(BiTree t)
{
	if (!t)
		return 0;
	int front = -1, rear = -1;
	int L = 0, ans = 0;
	BiTree q[MAX];
	BiTree p;
	q[++rear] = t;
	while (front < rear)
	{
		p = q[++front];
		if(p->lchild)
			q[++rear]=p->lchild;
		if(p->rchild)
			q[++rear] = p->rchild;
		if (L == front)
		{
			ans++;
			L = rear;
		}
	}
	return ans;
}
int main()
{
	BiTree t;
	build__Tree(t);
	cout << "前序序列:" << endl;
	print(t); cout << endl;
	cout << "层高为:" << depth(t);
	return EXIT_SUCCESS;
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

是分子

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

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

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

打赏作者

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

抵扣说明:

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

余额充值