C++数据结构实验3.2 返回树的高度

#include <iostream>
/**2018数据结构实验3.2**/
#include <string>
#include <cstring>
using namespace std;

struct Node
{
	int data;
	Node *left_tree;
	Node *right_tree;
}node, *root;

//插入元素
bool Insert(Node *&r, int a)
{
	if (r == NULL)
	{
		r = new Node;
		r->data = a;
		r->left_tree = NULL;
		r->right_tree = NULL;
		return true;
	}

	if (r->data < a || r->data == a)
	{
		return Insert(r->right_tree, a);
	}
	if (r->data > a)
	{
		return Insert(r->left_tree, a);
	}

	return true;
}

//借助insert建立树
bool Build(Node * &r, int a[], int k)
{
	if (k == 0)return false;

	r = NULL;
	int i = 0;
	for (i; i < k; i++)
	{
		Insert(r, a[i]);
	}
	return true;
}

//查找树的高度
int findHeight(Node*& T)
{
	if (T == NULL) return 0;
	else
	{
		int m = findHeight(T->left_tree);
		int n = findHeight(T->right_tree);
		return (m > n) ? (m + 1) : (n + 1);
	}
}


int main()
{
	int i = 0, data,nn;
	cin >> nn;
	int k[20] = { 0 };
	int arr[20][100];
	for (int x = 0; x < nn; x++)
	{
		while (cin >> data)
		{
			arr[x][i++] = data;
			k[x]++;
			if (cin.get() == '\n')break;
		}
		i = 0;
	}

	root = new Node;
	for (int x = 0; x < nn; x++)
	{
		Build(root, arr[x], k[x]);
		int h = findHeight(root);
		cout << h << endl;
		root = new Node;
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值