Retour au sommaire
Le titre
Construire un arbre AVL (arbre de tri binaire équilibré).
Échantillon (peut être copié)
5
88 70 61 96 120
//output
70
7
88 70 61 96 120 90 65
//output
88
Points à noter
- Cette question est plus difficile. Si vous ne pouvez pas le faire à l'examen PAT, vous pouvez directement afficher la médiane. Vous pouvez réussir 5 des 7 points de test et obtenir 17 points.
- L'arbre AVL (arbre de tri binaire équilibré) doit satisfaire: ① est un arbre de tri binaire, c'est-à-dire que tous les nœuds du sous-arbre gauche de chaque nœud de l'arbre sont inférieurs au nœud, et que tous les nœuds du sous-arbre droit de chaque nœud sont supérieurs au Noeud ② La valeur absolue de la différence entre les hauteurs gauche et droite de chaque noeud ne peut pas dépasser 1
- Dans le processus de construction d'un arbre binaire équilibré, quatre situations doivent être tournées: LL, LR, RR, RL. Dans chaque cas, tournez à gauche ou à droite pour voir le code de référence ci-dessous. Dans la simulation d'écriture manuscrite, nous utilisons généralement la méthode d'échange, mais dans le code réel, nous pouvons directement attribuer la valeur.
Médiane directe (17 minutes)
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,data[25];
cin>>n;
for(int i=0;i<n;i++)scanf("%d",&data[i]);
sort(data,data+n);
printf("%d",data[n/2]);
return 0;
}
AVL
#include<bits/stdc++.h>
using namespace std;
struct node{
int v,height;
node *lc,*rc;
}*root;
node* newnode(int v){
node* no=new node;
no->v=v;
no->height=1;
no->lc=no->rc=NULL;
return no;
}
int getheight(node* root){
if(root==NULL)return 0;
return root->height;
}
int getbalancenum(node* root){
return getheight(root->lc)-getheight(root->rc);
}
void L(node* &root){
node* tmp=root->rc;//tmp为新的root
root->rc=tmp->lc;//把tmp->rc裁剪下来
tmp->lc=root;
//只有root和tmp的高度发生了变化
root->height=max(getheight(root->lc),getheight(root->rc))+1;
tmp->height=max(getheight(tmp->lc),getheight(tmp->rc))+1;
root=tmp;
}
void R(node* &root){
node* tmp=root->lc;
root->lc=tmp->rc;
tmp->rc=root;
root->height=max(getheight(root->lc),getheight(root->rc))+1;
tmp->height=max(getheight(tmp->lc),getheight(tmp->rc))+1;
root=tmp;
}
void insert(node* &root,int v){
if(root==NULL){
root=newnode(v);
return;
}
if(v<root->v){
insert(root->lc,v);
root->height=max(getheight(root->lc),getheight(root->rc))+1;
if(getbalancenum(root)==2){
if(getbalancenum(root->lc)==1){//LL型
R(root);//右旋
}else if(getbalancenum(root->lc)==-1){//LR型
L(root->lc);//先左旋
R(root);//再右旋
}
}
}else{
insert(root->rc,v);
root->height=max(getheight(root->lc),getheight(root->rc))+1;
if(getbalancenum(root)==-2){
if(getbalancenum(root->rc)==-1){//RR型
L(root);//左旋
}else if(getbalancenum(root->rc)==1){//RL型
R(root->rc);//先右旋
L(root);//再左旋
}
}
}
}
int main(){
int n,v;
cin>>n;
while(n--){
cin>>v;
insert(root,v);
}
printf("%d\n",root->v);
return 0;
}