平衡搜索树 c

#include<stdio.h>
#include<stdlib.h>

struct tree{
    int data;
    struct tree*left,*right;
    int height;
};

int GetHeight(struct tree*p){
    if(!p)
        return 0;
    else
        return p->height;
}

int Max(int a,int b){
    return a>b? a:b;
}

struct tree* SingleLeftRotation(struct tree* A){
    struct tree* B=A->left;
    A->left=B->right;
    B->right=A;
    A->height=Max(GetHeight(A->left),GetHeight(A->right))+1;
    B->height=Max(GetHeight(B->left),GetHeight(B->right))+1;
    return B;
}

struct tree*SingleRightRotation(struct tree* A){
    struct tree* B=A->right;
    A->right=B->left;
    B->left=A;
    A->height=Max(GetHeight(A->left),GetHeight(A->right))+1;
    B->height=Max(GetHeight(B->left),GetHeight(B->right))+1;
    return B;
}

struct tree*DoubleLeftRightRotation(struct tree* A){
    A->left=SingleRightRotation(A->left);
    return SingleLeftRotation(A);
}

struct tree*DoubleRightLeftRotation(struct tree*A){
    A->right=SingleRightRotation(A->right);
    return SingleLeftRotation(A);
}

struct tree* insert(struct tree*p,int Data){
    if(!p){
        p=(struct tree*)malloc(sizeof(struct tree));
        p->left=p->right=NULL;
        p->data=Data;
        p->height=0;
    }
    else if(Data<p->data){
        p->left=insert(p->left,Data);
        if(GetHeight(p->left)-GetHeight(p->right)==2){
            if(Data<p->left->data)
                p=SingleLeftRotation(p);
            else
                p=DoubleLeftRightRotation(p);
        }
    }
    else if(Data>p->data){
        p->right=insert(p->right,Data);
        if(GetHeight(p->right)-GetHeight(p->left)==2){
            if(Data>p->right->data)
                p=SingleRightRotation(p);
            else
                p=DoubleRightLeftRotation(p);
        }
    }
    if(p->left||p->right)
    p->height=Max(GetHeight(p->left), GetHeight(p->right))+1;
    return p;
}

struct tree* check(struct tree * p){
    printf("%d ",p->data);
    if(p->left)p->left=check(p->left);
    if(p->right)p->right=check(p->right);
    return p;
}

int main(){
    struct tree* head=NULL;
    int N,i,Data;
    scanf("%d",&N);
    for(i=0;i<N;i++){
        scanf("%d",&Data);
        head=insert(head,Data);
    }
    printf("\n");
    check(head);
    return 0;
}

来源于中国mooc–数据结构<>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值