您的位置:首页 > 其它

平衡二叉树(AVL)模板

2017-06-10 17:17 344 查看
模板代码:
#include <bits/stdc++.h>
using namespace std;

const int maxn = 1e2+5;
int data[maxn];
struct node{
int v,height;
node *lchild, *rchild;
};

node* newNode(int v){
node* Node = new node;
Node->v = v;
Node->height = 1;
Node->lchild = Node->rchild = NULL;
return Node;
}

int getHeight(node *root){
if (root == NULL) return 0;
else return root->height;
}

int getBlanceFactor(node* root){
return getHeight(root->lchild) - getHeight(root->rchild);
}
void upDateHeight(node *root){
root->height = max(root->lchild->height, root->rchild->height) + 1;
return ;
}

void search_v(node *root, int v){
if (root == NULL){
printf("search failed!!\n");
return;
}
if (v == root->v){
cout<<v<<endl;
}
else if (v < root->v){
search_v(root->lchild, v);
}
else{
search_v(root->rchild, v);
}
return;
}

void L(node* &root){//这里一定要加引用的符号,否则在改变根节点的时候不会影响全局~
node* temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
upDateHeight(root);
upDateHeight(temp);
root = temp;
return;
}
void R(node* &root){//这里一定要加引用的符号,否则在改变根节点的时候不会影响全局~
node* temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
upDateHeight(root);
upDateHeight(temp);
root = temp;
return;
}

void insert_node(node* &root, int v){
if(root == NULL){
root = newNode(v);
return;
}
if(v < root->v){
insert_node(root->lchild, v);
upDateHeight(root);
if (getBlanceFactor(root) == 2){
if (getBlanceFactor(root->lchild) == 1){
R(root);
}
else if(getBlanceFactor(root->lchild) == -1){
L(root->lchild);
R(root);
}
}
}
else{
insert_node(root->rchild, v);
upDateHeight(root);
if (getBlanceFactor(root) == -2){
if (getBlanceFactor(root->rchild) == -1){
L(root);
}
else if(getBlanceFactor(root->rchild) == 1){
R(root->rchild);
L(root);
}
}
}
return;
}
node* Create(int n){
node *root = NULL;
for (int i=0; i<n; i++){
insert_node(root, data[i]);
}
return root;

}

int main()
{
int n;
cin>>n;
for (int i=0; i<n; i++){
cin>>data[i];
}
node* root;
root = Create(n);
search_v(root, 5);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  平衡二叉树