1066 Root of AVL Tree (25 分)(******)(avl樹的建立全過程,左旋右旋)

#include <cstdio>
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 1001;

struct node
{
    int data,height;
    node*l,*r;
};

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

int getBalance(node* root)
{
    return (getHeight(root->l) - getHeight(root->r));
}

void upHeight(node* root)
{
    root->height = max(getHeight(root->l),getHeight(root->r))+1;
}

void LeftRotation(node*&root)
{
    node*temp = root->r;
    root->r = temp->l;
    temp->l = root;
    upHeight(root);
    upHeight(temp);
    root = temp;
}

void rightRotation(node*&root)
{
    node*temp = root->l;
    root->l = temp->r;
    temp->r = root;
    upHeight(root);
    upHeight(temp);
    root = temp;
}

node* newNode(int data)
{
    node*temp = new node;
    temp->data = data;
    temp->height = 1;
    temp->l = temp->r = NULL;
    return temp;
}

void insertT(node* &root,int data)
{
    if(root == NULL)
    {
        root = newNode(data);
        return;
    }
    if(data < root->data)
    {
        insertT(root->l,data);
        upHeight(root);
        if(getBalance(root) == 2)
        {
            if(getBalance(root->l) == 1)
                rightRotation(root);
            else if(getBalance(root->l) == -1)
            {
                LeftRotation(root->l);
                rightRotation(root);
            }
        }
    }
    else
    {
        insertT(root->r,data);
        upHeight(root);
        if(getBalance(root) == -2)
        {
            if(getBalance(root->r) == -1)
                LeftRotation(root);
            else if(getBalance(root->r) == 1)
            {
                rightRotation(root->r);
                LeftRotation(root);
            }
        }
    }
}


int main()
{
    int n;
    scanf("%d",&n);
    node*root = NULL;
    for(int i = 0;i<n;i++)
    {
        int temp;
        scanf("%d",&temp);
        insertT(root,temp);
    }
    printf("%d",root->data);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章