zoukankan      html  css  js  c++  java
  • 1066 Root of AVL Tree

    link

    #include <bits/stdc++.h>
    # define LL long long
    using namespace std;
    
    class TreeNode{
    public:
        int val;
        TreeNode* left;
        TreeNode* right;
    
        TreeNode(int v):val{v},left{NULL},right{NULL}{}
    
        int getHeight(){
            int left=this->left==NULL?0:this->left->getHeight();
            int right=this->right==NULL?0:this->right->getHeight();
            return 1+max(left,right);
        }
    
        int leftHeight(){
            if(this->left==NULL) return 0;
            return this->left->getHeight();
        }
    
        int rightHeight(){
            if(this->right==NULL) return 0;
            return this->right->getHeight();
        }
    
        void add(int n){
            if(n<this->val){
                if(this->left==NULL){
                    this->left=new TreeNode(n);
                }else{
                    this->left->add(n);
                }
            }else{
                if(this->right==NULL){
                    this->right=new TreeNode(n);
                }else{
                    this->right->add(n);
                }
            }
            if(this->leftHeight()-this->rightHeight()>1){
                if(this->left->rightHeight()>this->left->leftHeight()){
                    this->left->leftRotate();
                }
                this->rightRotate();
                return;
            }
    
            if(this->rightHeight()-this->leftHeight()>1){
                if(this->right->leftHeight()>this->right->rightHeight()){
                    this->right->rightRotate();
                }
                this->leftRotate();
            }
        }
    
        void leftRotate(){
            TreeNode* newNode=new TreeNode(this->val);
            newNode->left=this->left;
            newNode->right=this->right->left;
            this->val=this->right->val;
            this->left=newNode;
            this->right=this->right->right;
        }
    
        void rightRotate(){
            TreeNode* newNode=new TreeNode(this->val);
            newNode->right=this->right;
            newNode->left=this->left->right;
            this->val=this->left->val;
            this->right=newNode;
            this->left=this->left->left;
        }
    };
    
    int main(){
        int N;
        scanf("%d", &N);
        int r=0;
        scanf("%d", &r);
        TreeNode* root=new TreeNode(r);
        for(int i=1;i<=N-1;i++){
            scanf("%d", &r);
            root->add(r);
        }
        cout<<root->val;
        return 0;
    }
  • 相关阅读:
    LeetCode_143. 重排链表
    LeetCode_844. 比较含退格的字符串
    LeetCode116. 填充每个节点的下一个右侧节点指针
    1002. 查找常用字符
    贝叶斯定理(Bayes' theorem)的理解笔记
    汉明码
    超级好用 音乐可视化软件-Specinker
    安卓安装aidlearning
    windows下gcc的安装和使用
    ubuntu桌面配置
  • 原文地址:https://www.cnblogs.com/FEIIEF/p/12426277.html
Copyright © 2011-2022 走看看