PAT 1066【AVL 建树与维护】

(⊙v⊙)嗯。。。

原先一直不知道AVL为什么有的时候要旋两次。。。这下懂啦!

AVL详情查看:http://dongxicheng.org/structure/avl/

看图比较好懂。恩。

自己手算一下就知道为什么插入在左子树的右子树上/左子树是不一样的。还是很好理解的,但是不要光看不动手啊啊啊。

然后就是,注意指针也是一个变量,如果把它作为参数放入函数中不带引用的话,那么就算在函数内开辟新空间了,函数结束后指针指向的还是NULL,而且这样会发生内存泄露!


#include <stdio.h>
#include <stdlib.h>
int max(int x,int y){return x>y?x:y;}
class node
{
public:
    int val;
    node *left,*right;
    node(int x):val(x),left(NULL),right(NULL){}
};
class Tree
{
public:
    node *root;
    void insert(int x,node *&p)
    {
        if(!p) {p=new node(x);return;}
        int h=0;
        if(x>p->val)
        {
            insert(x,p->right);
            if(!isbalance(p,h))
            {
                if(x>p->right->val) l_rotation(p);
                else rl_rotation(p);
            }
        }
        if(x<p->val)
        {
            insert(x,p->left);
            if(!isbalance(p,h))
            {
                if(x<p->left->val) r_rotation(p);
                else lr_rotation(p);
            }
        }
    }
    bool isbalance(node *tmp,int &h)
    {
        if(!tmp) return true;
        int l=0,r=0;
        bool ret=isbalance(tmp->left, l)&&isbalance(tmp->right, r);
        if(ret) h=max(l,r)+1;
        return ret&&(abs(l-r)<=1);
        
    }
    void l_rotation(node *&p)
    {
        node *tmp=p->right;
        p->right=tmp->left;
        tmp->left=p;
        p=tmp;
    }
    void r_rotation(node *&p)
    {
        node *tmp=p->left;
        p->left=tmp->right;
        tmp->right=p;
        p=tmp;      //注意这里!!!!! p指向的应该是当前的root节点了
    }
    void rl_rotation(node *&p)
    {
        r_rotation(p->right);
        l_rotation(p);
    }
    void lr_rotation(node *&p)
    {
        l_rotation(p->left);
        r_rotation(p);
    }
    void debug(node *p)
    {
        if(!p) return;
        printf("%d ",p->val);
        debug(p->left);
        debug(p->right);
    }
};
int main()
{
    int n,x;
    while(scanf("%d",&n)!=EOF)
    {
        Tree que;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&x);
            que.insert(x,que.root);
            //que.debug(que.root);printf("\n");
        }
        printf("%d\n",que.root->val);
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值