设为首页 加入收藏

TOP

平衡二叉树(AVL)
2018-12-13 18:08:44 】 浏览:52
Tags:平衡 AVL

AVL就是优化二叉查找树

平衡因子不大于1

左 < 根 < 右

 

具体看代码

#include<bits/stdc++.h>

using namespace std;
typedef struct node;
typedef node * tree;
struct node
{
    int v;
    int heigh;
    tree L,R;
};

//获取以root为根结点的子树的当前height
int getheigh(tree root)
{
    if(root==NULL) return 0;
    return root->heigh;
}

//更新结点root的heigh
void updataheigh(tree root)
{
    //max(左孩子结点的height,有孩子结点的height)+1
    root->heigh=max(getheigh(root->L),getheigh(root->R))+1;
}


//计算平衡因子
int getBalance(tree root)
{
    //左-右
    return getheigh(root->L)-getheigh(root->R);
}


//左旋  注意原理 对于RR是root的右孩子的平衡因子是-1
void L(tree &root)
{
    tree temp;
    temp=root->R;
    root->R=temp->L;
    temp->L=root;
    updataheigh(root);
    updataheigh(temp);
    root=temp;
}

void R(tree &root)
{
    tree temp;
    temp=root->L;
    root->L=temp->R;
    temp->R=root;
    updataheigh(root);
    updataheigh(temp);
    root=temp;
}
void insertt(tree &root,int v)
{
    if(root==NULL){//当结点是空的时候 就是插入的时候
        root=new node;
        root->v=v;
        root->heigh=1;
        root->L=root->R=NULL;
        return;
    }
    if(v<root->v){
        insertt(root->L,v);
        updataheigh(root);//注意更新树高
        if(getBalance(root)==2){
            if(getBalance(root->L)==1){
                R(root);
            }
            else if(getBalance(root->L)==-1){
                L(root->L);
                R(root);
            }
        }
    }
    else{
        insertt(root->R,v);
        updataheigh(root);
        if(getBalance(root)==-2){
            if(getBalance(root->R)==-1){
                L(root);
            }
            else if(getBalance(root->R)==1){
                R(root->R);
                L(root);
            }
        }
    }

}
int main()
{
    int n;
    scanf("%d",&n);
    int x;
    tree root;
    root=NULL;
    for(int i=0;i<n;i++){
        scanf("%d",&x);
        insertt(root,x);
    }
    printf("%d\n",root->v);
    return 0;
}

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇学习 Qt 编程的好书精品推荐! 下一篇new会返回NULL空指针吗

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目