PAT1066 Root of AVL Tree

54 篇文章 1 订阅

原文链接:我的个人博客

原题链接

1066 Root of AVL Tree

考点

  AVL树

思路

  主要考查的就是平衡二叉树。可以先看这篇文章

代码

#include <iostream>
#include <cmath>
using namespace std;
struct node{
    int key;
    node *left,*right;
};
//左旋 
node* leftRotate(node *tree){
    node* tmp = tree->right;//保存右子树,新的根 
    tree->right = tmp->left;//更新原来根节点的右子树 
    tmp->left = tree;//将原来的根节点作为新的根节点的左孩子 
    return tmp; //返回新的根节点 
}
//右旋 
node* rightRotate(node *tree){
    node* tmp= tree->left;//保存根的左子树,即为新的根 
    tree->left = tmp->right;//跟新原来根的左子树 
    tmp->right = tree;//更新 新的根的右子树 
    return tmp; //返回新的根节点 
} 
node* LR(node *tree){
    tree->left = leftRotate(tree->left);//先对根的左子树左旋
    return rightRotate(tree);//再右旋根节点 
} 
node* RL(node *tree){
    tree->right = rightRotate(tree->right);
    return leftRotate(tree);
}
//获取高度 
int getHeight(node *tree){
    if(tree==NULL) return 0;
    int l = getHeight(tree->left);
    int r = getHeight(tree->right);
    return max(l,r) +1;
}
node* build(node *root,int val){//向根节点root插入val 
    if(root==NULL){
        root = new node();
        root->key = val;
    }else if(val <root->key){//在左子树上char 
        root->left = build(root->left,val);
        int l = getHeight(root->left);
        int r = getHeight(root->right);
        if(abs(l-r)>=2){
            if(val < root->left->key){//在左子树的左子树上插入导致不平衡 
                root=rightRotate(root); 
            }else{//在左子树的右子树上插入导致不平衡 
                root=LR(root);
            }
        }
    }else{//在右子树上 
        root->right = build(root->right,val);
        int l = getHeight(root->left);
        int r = getHeight(root->right);
        if(abs(l-r)>=2){
            if(val < root->right->key){//在右子树的左子树上插入导致不平衡 
                root=RL(root); 
            }else{//在右子树的右子树上插入导致不平衡 
                root=leftRotate(root);
            }
        }
    }
    return root;
}
int main(){
    int n,tmp;
    cin>>n;
    node *root=NULL;
    for(int i=0;i<n;i++){
        cin>>tmp;
        root = build(root,tmp);//建树 
    }
    cout<<root->key; 
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值