avl树的基本操作

#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
struct node{
    int v,height; //v为节点的权值,height为当前子树的高度
    node *lchild,*rchild; //左右子树结点地址
} *root;
// 新建根节点
node* newNode(int v){
    node* Node=new node;
    Node->v=v;
    Node->height=1;
    Node->lchild=Node->rchild=NULL;
    return Node;
}
// 获取树的高度
int getHeight(node* root){
    if(root==NULL)
        return 0;
    return
        root->height;
}
// 更新树的高度
void updateHeight(node* root){
    root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
}
// 判断树是否平衡
int getBalanceFactor(node* root){
    return getHeight(root->lchild)-getHeight(root->rchild);
}
//左旋
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 v){
    if(root==NULL){
        root=newNode(v);
        return ;
    }
    if(v<root->v){
        insert(root->lchild,v);
        updateHeight(root);
        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,v);
        updateHeight(root);
        if(getBalanceFactor(root)==-2){
            if(getBalanceFactor(root->rchild)==-1){ //RR型
                L(root);
            } else if(getBalanceFactor(root->rchild)==1){ //RL型
                R(root->rchild);
                L(root);
            }
        }
    }
}
// 将avl树的节点层序遍历输出
void Layerorder(node* root){
    queue<node*> q;
    q.push(root);
    while(!q.empty()){
        node* now=q.front();
        printf("%d ",now->v);
        q.pop();
        if(now->lchild!=NULL)
            q.push(now->lchild);
        if(now->rchild!=NULL)
            q.push(now->rchild);
    }
}
int main(){
    int n,v;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&v);
        insert(root,v);
    }
    Layerorder(root);
    return 0;
}
/*5
88 70 61 63 65*/
/*8
88 70 61 96 120 90 65 68*/

猜你喜欢

转载自blog.csdn.net/qq_36926514/article/details/80273322
今日推荐