AVL建树模板

代码看着很多,但其实很多代码都是对称出现的,理解了AVL的建树思路之后,应该还是比较好记忆的

#include
#include
using namespace std;
struct node {
    int v, height;
    node *lchild, *rchild;
}*root;
//建立新结点
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;
    }
    return root->height;
}
//更新结点高度
void updatahegiht(node* root) {
    root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
//获取结点平衡因子
int getbalancefac(node* root) {
    return getHeight(root->lchild) - getHeight(root->rchild);
}
//队结点子树进行左旋
void L(node* &root) {
    node* temp = root->rchild;
    root->rchild = temp->lchild;
    temp->lchild = root;
    updatahegiht(root);
    updatahegiht(temp);
    root = temp;
}
//队结点子树进行右旋
void R(node* &root) {
    node* temp = root->lchild;
    root->lchild = temp->rchild;
    temp->rchild = root;
    updatahegiht(root);
    updatahegiht(temp);
    root = temp;
}
//插入结点
void insert(node* &root, int v) {
    if(root == NULL) {
        root = newnode(v);
        return ;
    }
    if(v < root->v) {
        insert(root->lchild, v);
        updatahegiht(root);
        if(getbalancefac(root) == 2) {
            if(getbalancefac(root->lchild) == 1) {
                R(root);
            } else if(getbalancefac(root->lchild) == -1) {
                L(root->lchild);
                R(root);
            }
        }
    } else {
        insert(root->rchild, v);
        updatahegiht(root);
        if(getbalancefac(root) == -2) {
            if(getbalancefac(root->rchild) == -1) {
                L(root);
            } else if(getbalancefac(root->rchild) == 1) {
                R(root->rchild);
                L(root);
            }
        }
    }
}
int main() {
    int n;
    cin >> n;
    for(int i = 0; i < n; i++) {
    	int v;
        cin >> v;
        insert(root, v);
    }
    return 0;
}

你可能感兴趣的:(AVL建树模板)