PAT A1066 Root of AVL Tree(AVL模版)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
模版题:

#include<bits/stdc++.h>
using namespace std;

typedef struct Node* Bintree;

struct Node
{
    int data,height;
    Bintree left,right;
};
Bintree root;

Bintree newNode(int data)
{
    Bintree Node=(Bintree)malloc(sizeof(struct Node));
    Node->data=data;
    Node->height=1;
    Node->left=NULL;
    Node->right=NULL;
    return Node;
}

int getHeight(Bintree root)
{
    if(root==NULL) return 0;
    return root->height;
}

void updateHeight(Bintree root)
{
    root->height=max(getHeight(root->left),getHeight(root->right))+1;
}

int getBalanceFactor(Bintree root)
{
    return getHeight(root->left)-getHeight(root->right);
}

void L(Bintree &root)
{
    Bintree temp=root->right;
    root->right=temp->left;
    temp->left=root;
    updateHeight(root);
    updateHeight(temp);
    root=temp;
}

void R(Bintree &root)
{
    Bintree temp=root->left;
    root->left=temp->right;
    temp->right=root;
    updateHeight(root);
    updateHeight(temp);
    root=temp;
}

void insert(Bintree &root,int v)
{
    if(root==NULL)
    {
        root=newNode(v);
        return;
    }

    if(v<root->data)
    {
        insert(root->left,v);
        updateHeight(root);
        if(getBalanceFactor(root)==2)
        {
            if(getBalanceFactor(root->left)==1)
            {
                R(root);
            }
            else if(getBalanceFactor(root->left)==-1)
            {
                L(root->left);
                R(root);
            }
        }
    }
    else if(v>root->data)
    {
        insert(root->right,v);
        updateHeight(root);
        if(getBalanceFactor(root)==-2)
        {
            if(getBalanceFactor(root->right)==-1)
            {
                L(root);
            }
            else if(getBalanceFactor(root->right)==1)
            {
                R(root->right);
                L(root);
            }
        }
    }
}

Bintree create(int data[],int n)
{
    Bintree root=NULL;
    for(int i=0;i<n;i++)
    {
        insert(root,data[i]);
    }

    return root;
}

int main()
{
    int n,v;
    int data[25];
    scanf("%d",&n);
    // for(int i=0;i<n;i++)
    // {
    //     scanf("%d",&data[i]);
    // }

    // root=create(data,n);
    // printf("%d",root->data);

    for(int i=0;i<n;i++)
    {
        scanf("%d",&v);
        insert(root,v);

    }

    printf("%d",root->data);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值