平衡二叉树(AVL)模板

这篇博客介绍了AVL树的基本操作,包括如何创建、插入节点,并在插入后进行平衡调整。提供了完整的C++代码实现,展示了如何处理左旋、右旋以及双旋转以保持树的平衡。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模板代码:
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值