#include <iostream>
#include<fstream>
using namespace std;
typedef struct
{
string name;
int age;
}Elemtype;
typedef struct BiTNode
{ //结点定义
Elemtype data;
int height;//高度,表示以当前结点为根的子树的高度
struct BiTNode* lchild, * rchild;
} BiTNode, * BiTree;
BiTNode* createNewNode(Elemtype &v)
{ //创建一个新结点
BiTNode* p = new BiTNode;
p->data = v;
p->height = 1;//结点的初始高度置为1
p->lchild = p->rchild = NULL;
return p;
}
int getHeight(BiTNode* &root)
{ //得到以结点root为根的树的高度
if (root == NULL) return 0;
else return root->height;
}
int getBalanceFactor(BiTNode* &root)
{ //求以结点root为根的树的平衡因子
return getHeight(root->lchild) - getHeight(root->rchild);
}
void updataHeight(BiTNode* &root)
{ //更新树的高度
root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
void leftRotation(BiTree& T)
{ //左旋
BiTNode* temp = T->rchild;
T->rchild = temp->lchild;
temp->lchild = T;
updataHeight(T);
updataHeight(temp);
T = temp;
}
void rightRotation(BiTree& T)
{ //右旋
BiTNode* temp = T->lchild;
T->lchild = temp->rchild;
temp->rchild = T;
updataHeight(T);
updataHeight(temp);
T = temp;
}
void insertAVL(BiTree& T, Elemtype &v)
{ //插入结点
if (T == NULL) {
T = createNewNode(v);
return;
}
if (T->data.age > v.age) {
insertAVL(T->lchild, v);
updataHeight(T);
if (getBalanceFactor(T) == 2)
{//左子树插入节点,发生不平衡时平衡因子为2
if (getBalanceFactor(T->lchild) == 1)
rightRotation(T); //LL型,右旋
else if (getBalanceFactor(T->lchild) == -1)
{ //LR型
leftRotation(T->lchild);//先左旋
rightRotation(T);//再右旋
}
}
}
else {
insertAVL(T->rchild, v);
updataHeight(T);
if (getBalanceFactor(T) == -2) {
//右子树插入节点,发生不平衡时平衡因子为-2
if (getBalanceFactor(T->rchild) == -1)
leftRotation(T);//RR型
else if (getBalanceFactor(T->rchild) == 1)
{ //RL型
rightRotation(T->rchild);//先右旋
leftRotation(T);//再左旋
}
}
}
}
BiTree createAVL(int n, Elemtype data[])
{ //创建AVL树
BiTree T = NULL;
for (int i = 0; i < n; ++i) {
insertAVL(T, data[i]);
}
return T;
}
void InOrderTraverse(BiTree T)
{ //中序遍历
if (T != NULL) {
InOrderTraverse(T->lchild);//访问左子树
cout <<"姓名为: " << T->data.name<<" 年龄为: " << T->data.age << " 平衡因子为 : " << getBalanceFactor(T) << endl; //访问根结点
InOrderTraverse(T->rchild);//访问右子树
}
}
void Search(BiTree& T,int &age,string &name)
{//AVL树查找
if(T)
{
if (age > T->data.age)
{
Search(T->rchild, age,name);
}
else if (age < T->data.age)
{
Search(T->lchild, age,name);
}
else (age==T->data.age)
{
name = T->data.name;
}
}
}
int main()
{
Elemtype* W = new Elemtype[100];
ifstream ifs;
ifs.open("worker.txt", ios::in);
int i = 0;
while (ifs)
{
ifs >> W[i].name;
ifs >> W[i].age;
i++;
}
BiTree T = createAVL(i-1, W);
cout << "中序遍历结果:" << endl;
InOrderTraverse(T);
int age;
cout << "请输入要查询的员工的年龄" << endl;
cin >> age;
string name = " ";
Search(T, age, name);
if (name != " ")
cout << "查询成功姓名为: " << name << endl;
else
cout << "查询失败无当前年龄的员工" << endl;
system("pause");
return 0;
}
平衡二叉树查找
于 2021-06-19 15:34:42 首次发布