平衡二叉树的几个基本操作
#include<iostream>
#include<algorithm>
using namespace std;
//平衡二叉树(AVL)
class node
{
public:
int data,height;
node*lchild;
node*rchild;
node(int data)
{
this->data=data;
height=1;
lchild=rchild= nullptr;
}
};
//得到当前结点的高度
int getHeight(node*root)
{
if(root==nullptr)
{
return 0;
}
return root->height;
}
//得到当前结点的平衡因子,平衡因子等于左子树的高度减去右子树的高度
int getBalanceFactor(node*root)
{
return getHeight(root->lchild)-getHeight(root->rchild);
}
//更新当前结点的高度,在插入了新的结点之后或者进行左旋或者右旋,可以用上这个函数
void updateHeight(node*root)
{
root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
}
//平衡二叉树的查找和二叉查找树一样
void search(node*root,int x)
{
if(root==nullptr)
{
cout<<"查找失败"<<endl;
return;
}
if(root->data==x)
{
cout<<root->data<<endl;
}
else if(root->data>x)
{
search(root->lchild,x);
}
else
{
search(root->rchild,x);
}
}
//树的左旋
void L(node*&root)
{
node*temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
updateHeight(root);
updateHeight(temp);
root=temp;
}
//树的右旋
void R(node*&root)
{
node*temp=root->lchild;
root->lchild=temp->rchild;
temp->rchild=root;
updateHeight(root);
updateHeight(temp);
root=temp;
}
//平衡二叉树的插入
void insert(node*&root,int x)
{
if(root==nullptr)
{
root=new node(x);
return;
}
if(root->data>x)
{
insert(root->lchild,x);
updateHeight(root);
//平衡因子只能为1,0,-1,等于2就说明失衡了
//这是在左子树,所以情况分为LL型,LR型
if(getBalanceFactor(root)==2)
{
if(getBalanceFactor(root->lchild)==1)//LL型
{
R(root);
}
else if(getBalanceFactor(root->lchild)==-1)//LR型
{
L(root->lchild);
R(root);
}
}
}
else
{
insert(root->rchild,x);
updateHeight(root);
//这是在右子树,所以情况分为RR型,RL型
if(getBalanceFactor(root)==-2)
{
if(getBalanceFactor(root->rchild)==-1)//RR型
{
L(root);
}
else if(getBalanceFactor(root->rchild)==1)//RL型
{
R(root->rchild);
L(root);
}
}
}
}
node*create(int data[],int n)
{
node*root=nullptr;
for(int i=0;i<n;i++)
{
insert(root,data[i]);
}
return root;
}