标签:get pac getheight ems std space 关键点 cpp 等于
链接
建立一棵AVL树,输出根结点
#include<bits/stdc++.h>
using namespace std;
const int maxn = 25;
int n, a[maxn];
struct node{
int w,h;
node *lchild, *rchild;
}nodes[maxn];
int getHeight(node *root){
if(root == NULL) return 0;
return root->h;
}
void updateHeight(node *root){
if(root == NULL) return;
//不是直接写root->lchild->h
root->h = max(getHeight(root->lchild), getHeight(root->rchild)) + 1; //注意!!!
}
int getBF(node *root){
return getHeight(root->lchild) - getHeight(root->rchild);
}
void L(node *&root){//一定不要忘记加引用
node *temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void R(node *&root){//一定不要忘记加引用
node *temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void insert(node *&root, int x){ //一定不要忘记加引用
if(!root){
root = new node;
root->w = x;
root->h = 1; //不要忘记高度
root->lchild = root->rchild = NULL; //不要忘记NULL
return;
}
if(x < root->w){
insert(root->lchild, x);
updateHeight(root);
if(getBF(root) == 2){
if(getBF(root->lchild) == 1) R(root);
else if(getBF(root->lchild) == -1){
L(root->lchild);
R(root);
}
}
}else{
insert(root->rchild, x);
updateHeight(root);
if(getBF(root) == -2){
if(getBF(root->rchild) == -1) L(root);
else if(getBF(root->rchild) == 1){
R(root->rchild);
L(root);
}
}
}
}
node *create(){
node *root = NULL;
for(int i=0;i<n;i++){
insert(root, a[i]);
}
return root;
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
node *root = create();
cout<<root->w<<endl;
}
PAT A1066 Root of AVL Tree [平衡二叉树]
标签:get pac getheight ems std space 关键点 cpp 等于
原文地址:https://www.cnblogs.com/doragd/p/11272831.html