1066 Root of AVL Tree (25)(25 分)

二叉树旋转操作,这个只能记一下怎么旋转了

#include<iostream>
#include<algorithm>
using namespace std;
int n;
struct node {
    int data;
    node *lchild, *rchild;
};
node* Newnode(int x)
{
    node* newnode = new node;
    newnode->data = x;
    newnode->lchild = newnode->rchild = NULL;
    return newnode;
}
int Height(node* root)
{
    if (root == NULL)return 0;
    else return max(Height(root->lchild), Height(root->rchild)) + 1;
}
int getbalance(node* root)
{
    return Height(root->lchild) - Height(root->rchild);
}
void R(node*&root)
{
    node* temp = root->lchild;
    root->lchild = temp->rchild;
    temp->rchild = root;
    root = temp;
}
void L(node*&root)
{
    node* temp = root->rchild;
    root->rchild = temp->lchild;
    temp->lchild = root;
    root = temp;
}
void insert(node* &root, int x)
{
    if (root == NULL)
    {
        root = Newnode(x);
        return;
    }
    if (x < root->data)
    {
        insert(root->lchild, x);
        if (getbalance(root) == 2)
        {
            if (getbalance(root->lchild) == 1)
            {
                R(root);
            }
            else if (getbalance(root->lchild) == -1)
            {
                L(root->lchild);
                R(root);
            }
        }
    }
    else
    {
        insert(root->rchild, x);
        if (getbalance(root) == -2)
        {
            if (getbalance(root->rchild) == -1)L(root);
            else if (getbalance(root->rchild) == 1)
            {
                R(root->rchild);
                L(root);
            }
        }

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 小时候特别羡慕自然的玄奇与瑰丽,所以在心里也喜欢的无与伦比。因为未知与神秘,所以对大自然的向往充满了一颗少年的心。...
    子修些许阅读 3,081评论 0 4
  • 因为我太闲,所以我的微博不断的更新着 因为我太闲,群里最活跃就是我 因为我太闲,朋友的微信从来都是秒回 因为我太闲...
    三木呐阅读 1,144评论 0 0
  • 1.看延迟:打开任务管理器——性能——打开资源监视器——网络——TCP链接。 2.kephrii 眼动
    hypercode阅读 775评论 0 0
  • 之前在给项目适配64位时,看到Xcode中有这个设置,因为关系到适配问题,又比较好奇,就了解了一番。发现这个设置也...
    WheatDen阅读 4,681评论 0 1
  • 花开有声(修改稿) 文/岐麟散人(陕西宝鸡) 日月轮回百花开, 春夏秋冬景全来, 万紫千红添色彩, 残絮飞落上青苔...
    岐麟散人阅读 3,188评论 0 1

友情链接更多精彩内容