zoukankan      html  css  js  c++  java
  • 1066 Root of AVL Tree (25 分)(平衡二叉树)

    就是AVL的模板题了 注意细节

    #include<bits/stdc++.h>
    
    using namespace std;
    typedef struct node;
    typedef node * tree;
    struct node
    {
        int v;
        int heigh;
        tree L,R;
    };
    
    int getheigh(tree root)
    {
        if(root==NULL) return 0;
        return root->heigh;
    }
    
    void updataheigh(tree root)
    {
        root->heigh=max(getheigh(root->L),getheigh(root->R))+1;
    }
    
    int getBalance(tree root)
    {
        return getheigh(root->L)-getheigh(root->R);
    }
    
    void L(tree &root)
    {
        tree temp;
        temp=root->R;
        root->R=temp->L;
        temp->L=root;
        updataheigh(root);
        updataheigh(temp);
        root=temp;
    }
    
    void R(tree &root)
    {
        tree temp;
        temp=root->L;
        root->L=temp->R;
        temp->R=root;
        updataheigh(root);
        updataheigh(temp);
        root=temp;
    }
    void insertt(tree &root,int v)
    {
        if(root==NULL){
            root=new node;
            root->v=v;
            root->heigh=1;
            root->L=root->R=NULL;
            return;
        }
        if(v<root->v){
            insertt(root->L,v);
            updataheigh(root);
            if(getBalance(root)==2){
                if(getBalance(root->L)==1){
                    R(root);
                }
                else if(getBalance(root->L)==-1){
                    L(root->L);
                    R(root);
                }
            }
        }
        else{
            insertt(root->R,v);
            updataheigh(root);
            if(getBalance(root)==-2){
                if(getBalance(root->R)==-1){
                    L(root);
                }
                else if(getBalance(root->R)==1){
                    R(root->R);
                    L(root);
                }
            }
        }
    
    }
    int main()
    {
        int n;
        scanf("%d",&n);
        int x;
        tree root;
        root=NULL;
        for(int i=0;i<n;i++){
            scanf("%d",&x);
            insertt(root,x);
        }
        printf("%d
    ",root->v);
        return 0;
    }
  • 相关阅读:
    Python一键安装缺失库
    Python画樱花树❀
    Python时间模块time
    Python的画五角星
    力扣225.用队列实现栈
    STL是个啥?
    如何使用递归遍历对象获得value值
    JS操作未跨域iframe里的DOM
    CSS3D效果
    前端轮播小结
  • 原文地址:https://www.cnblogs.com/chenchen-12/p/10114448.html
Copyright © 2011-2022 走看看