二叉树的平衡因子

二叉树T的结点结构为:data域,平衡因子bal,左子树结点,右子树结点
bal=左子树高度-右子树高度
编写算法求树T中bal值。(//(待定)各结点的bal值)

#include<iostream>
#include<vector>
using namespace std;
template<class T>
struct BiNode
{
	T data;
	int bal;
	BiNode<T>* lchild, * rchild;
};
template<class T>
class BiTree
{
	BiNode<T>* root;
	int Height(BiNode<T>*p);
	void Free(BiNode<T>* p);
	BiNode<T>* CreatByPre(vector<T>& pre, int& i);
	int lHeight(BiNode<T>* p);
	int rHeight(BiNode<T>* p);
public:
	BiTree(vector<T>&pre);
	~BiTree();
	int Height();
	
};
template<class T>
int BiTree<T>::rHeight(BiNode<T>* p)
{
	if (p == NULL)return 0;
	int right = rHeight(p->rchild);
	return right + 1;

}
template<class T>
int BiTree<T>::lHeight(BiNode<T>* p)
{
	if (p == NULL)return 0;
	int left = lHeight(p->lchild);
	return left + 1;
}
template<class T>
int BiTree<T>::Height()
{
	
	root->bal = lHeight(root) - rHeight(root);
	return root->bal;

}

template<class T>
BiNode<T>* BiTree<T>::CreatByPre(vector<T>& pre, int& i)
{
	T e = pre[i]; i++;
	if (e == '*')
		return NULL;
	BiNode<T>* p = new BiNode<T>;
	p->data = e;
	p->lchild = CreatByPre(pre, i);
	p->rchild = CreatByPre(pre, i);
	return p;
}
template<class T>
BiTree<T>::BiTree(vector<T>& pre)
{
	int i = 0;
	root = CreatByPre(pre, i);
}
template<class T>
void BiTree<T>::Free(BiNode<T>* p)
{
	if (p == NULL)
		return;
	Free(p->lchild);
	Free(p->rchild);
	delete p;

}
template<class T>
BiTree<T>::~BiTree()
{
	Free(root);
}
int main()
{

	char a[100] = { "abd**e**cf***" };

	vector<char>b(a, a + 13);
	//int i;
	BiTree<char>bb(b);
	cout << endl;
	int h = bb.Height();
	cout << "该二叉树的平衡因子为:"<<h<<endl;

	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值