二叉树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;
}