《平衡二叉树》

#include <bits/stdc++.h>
typedef struct node
{
    int data;
    struct node *l,*r;
}*tree;
int length(tree root)
{
    int cou=0,len1,len2;
    if(root)
    {
        len1=length(root->l);
        len2=length(root->r);
        if(len1>=len2)
        {
            cou=len1;
            cou++;
        }
        else
        {
            cou=len2;
            cou++;
        }
    }
    else
    {
       cou=0;
    }
    return cou;
}
tree RR(tree root) //  ROOT的右边,向左转
{
    tree p;
    p=root->r;
    root->r=p->l;
    p->l=root;
    return p;
}
tree LL(tree root)//  ROOT的左边,向右转
{
    tree p;
    p=root->l;
    root->l=p->r;
    p->r=root;
    return p;
}
tree RL(tree root)// ROOT的右边,先向右转在向左转
{
    root->r=LL(root->r);
    return RR(root);
}
tree LR(tree root) ROOT的左边,先向左转在向右转
{
    root->l=RR(root->l);
    return LL(root);
}
tree creat(int x,tree root)
{
    if(!root)
    {
        root=new node;
        root->l=NULL;
        root->r=NULL;
        root->data=x;
    }
    else if(x>root->data)
    {
        root->r=creat(x,root->r);
        if(length(root->r)-length(root->l)>1)
        {
            if(root->r->data<x)
                root = RR(root);
            else
                root = RL(root);
        }
    }
    else if(x<root->data)
    {
        root->l=creat(x,root->l);
        if(length(root->l)-length(root->r)>1)
        {
            if(root->l->data<x)
                root = LR(root);
            else
                root = LL(root);
        }

    }
    return root;
}
int main()
{
    int x,n;
    scanf("%d",&n);
    tree root;
    root=NULL;
    while(n--)
    {
        scanf("%d",&x);
        root=creat(x,root);
    }
    printf("%d\n",root->data);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42854569/article/details/81569627
今日推荐