码迷,mamicode.com
首页 > 其他好文 > 详细

1066 Root of AVL Tree

时间:2020-03-06 15:16:46      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:lse   its   root   https   inf   namespace   pre   add   idt   

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;
}

 

1066 Root of AVL Tree

标签:lse   its   root   https   inf   namespace   pre   add   idt   

原文地址:https://www.cnblogs.com/FEIIEF/p/12426277.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!