二叉平衡树(AVL)-C语言

本文介绍了一种自平衡二叉搜索树——AVL树,并详细解释了AVL树的单左旋转、单右旋转、右左旋转及左右旋转等操作。通过具体的C语言实现代码,展示了如何在AVL树中插入新节点并保持其平衡性。
#include <stdio.h>
#include <stdlib.h>

#define max(a,b) (a>=b?a:b)
#define min(a,d) (a<b?a:b)
#define N 7    //数组长度

/* 二叉平衡树AVL */
typedef int Elemtype;
typedef struct AVLNode
{
    Elemtype data;
    struct AVLNode *lchild, *rchild;
    int height;
}AVLNode,*PNode;

//获取结点高度
int height(PNode p)
{
    return p == NULL ? -1 : p->height;
 } 

//单左旋转
PNode LeftRotate(PNode k2)
{
    PNode k1 = k2->lchild;
    k2->lchild = k1->rchild;
    k1->rchild = k2;
    k2->height = max(height(k2->lchild),height(k2->rchild)) + 1;
    k1->height = max(height(k1->lchild),k2->height) + 1;
    return k1;
 } 

//单右旋转
PNode RightRotate(PNode k2)
 {
    PNode k1 = k2->rchild;
    k2->rchild = k1->lchild;
    k1->lchild = k2;
    k2->height = max(height(k2->lchild),height(k2->rchild)) + 1;
    k1->height = max(height(k1->lchild),k2->height) + 1;
    return k1;
  } 

//右左旋转
PNode doubleLeftRotate(PNode k3)
{
    k3->lchild =RightRotate(k3->lchild);
      return LeftRotate(k3); 
} 
//左右旋转
PNode doubleRightRotate(PNode k3)
{
    k3->rchild =LeftRotate(k3->rchild);
      return RightRotate(k3); 
} 
//  AVL树插入结点
PNode insertAVL(PNode root,Elemtype data)
{
    if(root == NULL)
    {
        root = (PNode)malloc(sizeof(AVLNode));
        root->data = data;
        root->lchild = NULL;
        root->rchild = NULL;
        printf("%d 插入AVL树\n",data);
        return root;
    }   

    if(data < root->data)
    {
        root->lchild = insertAVL(root->lchild,data);
        if(height(root->lchild)-height(root->rchild) == 2)
        {
            if(data < root->lchild->data)
                root = LeftRotate(root);
            else
                root = doubleLeftRotate(root);
        }
    }
    else if(data > root->data)
    {
        root->rchild = insertAVL(root->rchild,data);
        if(height(root->rchild)-height(root->lchild) == 2)
            if(data > root->rchild->data)
                root = RightRotate(root);
            else
                root = doubleRightRotate(root);
    }
    else
        printf("%d 已在树中\n");

    root->height = max(height(root->lchild),height(root->rchild)) + 1;
    return root;
} 

//中序遍历打印AVL树
void print(PNode root)
{
    if(root!=NULL)
    {
        print(root->lchild);
        printf("%d ",root->data);
        print(root->rchild);
    }
}

int main(int argc, char *argv[]) {
    PNode root = NULL;
    int data[N] = {1,2,3,4,1,6,7};
    int i;
    for(i =0;i<N;i++)
        root = insertAVL(root,data[i]);
    print(root);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值