原题
题目大意及思路
- **题目大意:**建一颗AVL树,输出根节点的值
代码
#include<iostream>
#include<cmath>
using namespace std;
struct node{
int v,height;
node *lchild,*rchild;
};
node * newNode(int value){
node *Node=new node;
Node->v=value;
Node->height=1;
Node->lchild=NULL;
Node->rchild=NULL;
return Node;
}
int getHeight(node *root){
if(root==NULL) return 0;
return root->height;
}
void updateHeight(node* root){
root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
return;
}
int getBalancedFacotr(node* root){
return getHeight(root->lchild)-getHeight(root->rchild);
}
void R(node* &root){
node *temp=root->lchild;
root->lchild=temp->rchild;
temp->rchild=root;
updateHeight(root);
updateHeight(temp);
root=temp;
return;
}
void L(node* &root){
node *temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
updateHeight(root);
updateHeight(temp);
root=temp;
return;
}
void insert(node* &root,int value){
if(root==NULL){
root=newNode(value);
return;
}
else if(root->v>value){
insert(root->lchild,value);
updateHeight(root);
if(getBalancedFacotr(root)==2){
if(getBalancedFacotr(root->lchild)==1){ //LL
R(root);
}
else if(getBalancedFacotr(root->lchild)==-1){ //LR
L(root->lchild);
R(root);
}
}
}
else{
insert(root->rchild,value);
updateHeight(root);
if(getBalancedFacotr(root)==-2){
if(getBalancedFacotr(root->rchild)==-1){ //RR
L(root);
}
else if(getBalancedFacotr(root->rchild)==1){ //RL
R(root->rchild);
L(root);
}
}
}
}
int main(){
int n;
cin>>n;
node * root=NULL;
for(int i=0;i<n;i++){
int data;
cin>>data;
insert(root,data);
}
printf("%d\n",root->v);
return 0;
}
运行截图
收获
学会了AVL树的构建、节点的插入以及不平衡后的操作:左旋 右旋