平衡二叉树的构建,做个笔记吧
#include <cstdio>
#include <algorithm>
struct node{
int data, height;
node *left, *right;
};
node* newNode(int e);
int getHeight(node *a);
void updateHeight(node *a);
int getBalanceFactor(node *a);
//a是失衡结点,左旋,使a的右子取代a,旋转后要接回到原树上,必须用引用
void leftRotate(node* &a);
//右旋
void rightRotate(node* &a);
//递归地插入结点,假设树中不存在重复值
void insertNode(node* &root, int e); //必须引用
node* createAVL(int data[], int n);
int main(){
int N;
scanf("%d", &N);
int data[N];
for(int i=0; i<N; i++) scanf("%d", &data[i]);
node *root = createAVL(data, N);
printf("%d", root->data);
return 0;
}
node* newNode(int e){
node *n = new node;
n->data = e;
n->left = n->right = NULL;
n->height = 1;
return n;
}
int getHeight(node *a){
if(a==NULL) return 0; //涉及到空结点,必须人为定义其高度为0
return a->height;
}
void updateHeight(node *a){
a->height = std::max(getHeight(a->left), getHeight(a->right)) + 1;
return;
}
int getBalanceFactor(node *a){
return getHeight(a->left) - getHeight(a->right);
}
void leftRotate(node* &a){
node *temp = a->right;
a->right = temp->left;
temp->left = a;
updateHeight(a);
updateHeight(temp);
a = temp; //接回原树
return;
}
void rightRotate(node* &a){
node *temp = a->left;
a->left = temp->right;
temp->right = a;
updateHeight(a);
updateHeight(temp);
a = temp; //接回原树
return;
}
void insertNode(node* &root, int e){
if(root==NULL){
root = newNode(e); //新结点高度已设,必平衡不用检查
return;
}
if(e>root->data){
insertNode(root->right, e); //在右子树中插入,插入后要检查root的平衡因子
updateHeight(root); //在插入路径上,更新除了新结点以外所有结点的高度
//在插入路径上,检查除了新结点以外所有结点的平衡因子
if(getBalanceFactor(root)==-2){
//在右子树中插入,只可能出现RR,RL型
if(getBalanceFactor(root->right)==-1){
//RR
leftRotate(root);
}
else if(getBalanceFactor(root->right)==1){
//RL
rightRotate(root->right);
leftRotate(root);
}
}
}
else{
insertNode(root->left, e);
updateHeight(root);
if(getBalanceFactor(root)==2){
//在左子树中插入,只可能出现LL,LR型
if(getBalanceFactor(root->left)==1){
//LL
rightRotate(root);
}
else if(getBalanceFactor(root->left)==-1){
//LR
leftRotate(root->left);
rightRotate(root);
}
}
}
return;
}
node* createAVL(int data[], int n){
node *root = NULL;
for(int i=0; i<n; i++) insertNode(root, data[i]);
return root;
}