平衡二叉树的基本操作

平衡二叉树的几个基本操作

#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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值