平衡二叉树(AVL树)的详细介绍:https://blog.csdn.net/qq_43643944/article/details/116354568
#include <iostream>
using namespace std;
typedef struct BiTNode { //结点定义
int data;
int height;//高度,表示以当前结点为根的子树的高度
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
BiTNode *createNewNode(int 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;
}
bool searchAVL(BiTree T, int x) {//AVL树的查找
if (T == NULL)
return false;
if (T->data == x)
return true;
if (T->data > x)
searchAVL(T->lchild, x);
if (T->data < x)
searchAVL(T->rchild, x);
}
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, int v) { //插入结点
if (T == NULL) {
T = createNewNode(v);
return;;
}
if (T->data > v) {
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, int 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 << " 平衡因子为 : " << getBalanceFactor(T) << endl; //访问根结点
InOrderTraverse(T->rchild);//访问右子树
}
}
int main() {
int data[10] = {10, 5, 30, 20, 15, 35, 50, 40, 45, 60};
BiTree T = createAVL(10, data);
cout << "中序遍历结果:" << endl;
InOrderTraverse(T);
return 0;
}