平衡二叉树是对排序二叉树的优化,在插入结点时有着很大的变化,需要调整树的高度达到平衡,下面是代码:
#include<iostream>
using namespace std;
struct node{
int v,height; //height 记录高度 这里的高度是从下往上记
node *lchild,*rchild;
};
node* newnode(int x){ //生成一个新结点
node* r=new node;
r->v=x;
r->height=1; //初始化高度为一
r->lchild=r->rchild=NULL;
return r;
}
int getheight(node* root) { // 得到当前结点的高度
if(root==NULL)return 0;
return root->height;
}
int getfactor(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==NULL){ //没有查到
printf("fail!\n");
return;
}
if(root->v==x){ //查到
printf("succeed!");
return;
}
if(root->v>x)search(root->lchild,x);
else search(root->rchild,x);
}
//为实现插入操作的四个旋
void L(node* &root) {//左旋,root的右孩子当根
node* temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
//更新这两个结点高度
updateheight(root);
updateheight(temp);
root=temp;//改变根结点
}
void R(node* &root) {//右旋,root的左孩子当根
node* temp=root->lchild;
root->lchild=temp->rchild;
temp->rchild=root;
updateheight(root);
updateheight(temp);
root=temp;
}
/*四种树形结论,看平衡因子
根为2 左孩子为1,LL型 右旋解决
左孩子为 -1,LR型 先左孩子左旋后root右旋解决
根为-2 右孩子-1,RR型 左旋解决
右孩子1,RL型 先右孩子右旋再root左旋解决
*/
void insert(node* &root,int x){
if(root==NULL){
root=newnode(x);
return;
}
if(x<root->v) {
insert(root->lchild,x);//往左子树插
updateheight(root);//更新高度
if(getfactor(root)==2) {
if(getfactor(root->lchild)==1)//LL型,右旋
R(root) ;
else { //LR型,左右旋
L(root->lchild) ;
R(root);
}
}
}
else{
insert(root->rchild,x);//往右子树插
updateheight(root);//更新高度
if(getfactor(root)==-2) {
if(getfactor(root->rchild)==-1)//RR型,左旋
L(root) ;
else { //RL型,右左旋
R(root->rchild) ;
L(root);
}
}
}
}
node * creating(int a[],int n){ //创建二叉树
node* root=NULL;
for(int i=0;i<n;i++)
insert(root,a[i]);
return root;
}
int main(){
return 0;
}
这里和排序二叉树的区别在于引入了高度好标记平衡因子,高度的更新操作比较重要,之后左、右旋,记录树形解决方法也是难点。