平衡二叉树

平衡二叉树

对AVL树的任意结点来说,其左子树与右子树的高度之差的绝对值不超过1,左子树与右子树的高度之差称为该结点的平衡因子。

1.结构
struct node{
    int v;//结点权值
    int height;//当前子树高度
    struct node* lchild,rchild; 
};
2.新建结点
struct node* newNode(int v){
    struct node* Node=new node;
    node->v=v;
    node->height=1;
    node->rchild=NULL;
    node->lchild=NULL;
    return Node;//返回新建结点的地址 
}
3.获取高度
int getHeight(struct node* root){
    if(root==NULL){
        return 0;//空结点高度为0 
    }
    return root->height; 
}
4.获取平衡因子 
int getBalance(struct node* root){
    return getHeight(root->lchild)-getHeight(root->rchild);
} 
5.更新height
void updata(struct node* root){
    root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
} 
6.查找
void search(struct node* root,int x){
    if(root==NULL){
        printf("search failed\n");
        return ;
    }
    if(x==root->data){
        printf("%d",root->data);
    }else if(xdata){
        search(root->lchild,x);
    }
    else{
        search(root->rchild,x);
    }
} 
7.插入
void insert(struct node*& root,int v){
    if(root==NULL){
        root=newNode(v);
        return ;
    }
    if(vdata){
        insert(root->lchild,v);
        update(root);
        if(getbalance(root)==2){
            if(getbalance(root->lchild)==1){
                R(root);
            }else if(getbalance(root->lchild)==-1){
                L(root->rchild);
                R(root);
            }
            
        }
    }
    else{
        insert(root->rchild,v);
        update(root->lchild);
        if(getbalance(root)==-2){
            if(getbalance(root->rchild)==-1){
                L(root);
            }else if(getbalance(root->rchild)==1){
                R(root->lchild);
                L(root);
            }
        }
    }
} 

8.左旋
void L(struct node*& root){
    struct node* temp=root->rchild;
    root->rchild=temp->lchild;
    temp->lchild=root;
    update(root);
    update(temp);
    root=temp;
} 
9.右旋
void L(struct node*& root){
    struct node* temp=root->lchild;
    root->lchild=temp->rchild;
    temp->rchild=root;
    update(root);
    update(temp);
    root=temp;
} 

你可能感兴趣的:(平衡二叉树)