各类平衡树的原理与应用

· · 算法·理论

前言

介绍

这篇文章是讲述各类平衡树的原理与应用的(不喜勿喷),例题P3369 【模板】普通平衡树

注:

本文章讲的某些基础数据结构(如二叉搜索树)不一定能通过例题,会说明

00.二叉搜索树

00.00 介绍

二叉搜索树是一种特殊的二叉树,其左子树内的值 < 根节点的值 < 右子树内的值,其左右子树也同样满足二叉搜索树的性质,例如下图: 易证:二叉搜索树的中序遍历是有序序列

00.01 查找

设要查找的数为 x , 用递归实现,分 4 种情况:

template<typename T> void maintain(BST_Node<T>*& root) { if (root == nullptr) return; int ls_siz = root->lson ? root->lson->siz : 0; int rs_siz = root->rson ? root->rson->siz : 0; root->siz = ls_siz + rs_siz + root->cnt; }

template<typename T> bool find(BST_Node<T>* root, T x) { if (root == nullptr) return false; if (x < root->val) return find(root->lson, x); if (x > root->val) return find(root->rson, x); return true; }

template<typename T> void insert(BST_Node<T>*& root, T x) { if (root == nullptr) { root = new BST_Node<T>(x); return; } if (x < root->val) insert(root->lson, x); else if (x > root->val) insert(root->rson, x); else root->cnt ++; maintain(root); }

template<typename T> BST_Node<T>& getMax(BST_Node<T>& root) { if (root->rson == nullptr) return root; auto &res = getMax(root->rson); maintain(root); return res; }

template<typename T> void remove(BST_Node<T>*& root, T x) { if (root == nullptr) return; if (x < root->val) remove(root->lson, x); else if (x > root->val) remove(root->rson, x); else { if (root->cnt > 1) { root->cnt --; } else { if (root->lson == nullptr && root->rson == nullptr) { delete root; root = nullptr; } else if (root->lson == nullptr) { auto tmp = root; root = root->rson; delete tmp; } else if (root->rson == nullptr) { auto tmp = root; root = root->lson; delete tmp; } else { auto &max_node = getMax(root->lson); root->val = max_node->val; root->cnt = max_node->cnt; max_node->cnt = 1; remove(max_node, max_node->val); } } } maintain(root); }

template<typename T> int get_rank(BST_Node<T>* root, T x) { if (root == nullptr) return 0; int ls_siz = root->lson ? root->lson->siz : 0; if (x <= root->val) { return get_rank(root->lson, x); } else { return ls_siz + root->cnt + get_rank(root->rson, x); } }

template<typename T> T kth(BST_Node<T>* root, int k) { int ls_siz = root->lson ? root->lson->siz : 0; if (k <= ls_siz) { return kth(root->lson, k); } else if (k <= ls_siz + root->cnt) { return root->val; } else { return kth(root->rson, k - ls_siz - root->cnt); } }

template<typename T> T get_pre(BST_Node<T>* root, T x) { T res = -(1 << 31); auto p = root; while (p != nullptr) { if (p->val < x) { res = p->val; p = p->rson; } else { p = p->lson; } } return res; }

template<typename T> T get_suc(BST_Node<T>* root, T x) { T res = 1 << 31; auto p = root; while (p != nullptr) { if (p->val > x) { res = p->val; p = p->lson; } else { p = p->rson; } } return res; }

不难发现插入,删除,查询的均摊时间复杂度都是 $ O(\log n) $ 
但是当输入数据本身有序是,树会退化成链,复杂度退化为 $ O(n) $,无法通过例题,如下图:
![](https://cdn.luogu.com.cn/upload/image_hosting/ytkwfdju.png)
因此我们引入了平衡树。
## 01.AVL树
B站:[@蓝不过海呀](https://www.bilibili.com/video/BV1tZ421q72h/?spm_id_from=333.1387.collection.video_card.click)
### 01.00 介绍
AVL树是一种特殊的二叉搜索树,通过特殊的旋转方式使平衡因子 $ F = h_l - h_r \in $ $ [-1,1] $,左右子树也满足AVL树的性质
例如下图:
![](https://cdn.luogu.com.cn/upload/image_hosting/972p6mkz.png)
### 01.01 查找
与二叉搜索树相同。
### 01.02 左右旋
旋转操作不破坏二叉搜索树性质,只改变树的拓扑形态,用来降低树高,接下来的很多平衡树也是依赖左右旋的,属于重点,接下来令操作对象为 $ x $,左孩子为 $ l $,右孩子为 $ r $
#### 01.02.00 左旋zag
将 $ r $ 提升为根节点,将 $ x $ 降级为 $ r $ 的左孩子,原本 $ r $ 的左孩子变成 $ x $ 的右孩子,如下图
![](https://cdn.luogu.com.cn/upload/image_hosting/1hslki5k.png)
![](https://cdn.luogu.com.cn/upload/image_hosting/kivloac9.png)
#### 01.02.01 右旋 zig
将 $ l $ 提升为根节点,将 $ x $ 降级为 $ l $ 的右孩子,原本 $ l $ 的右孩子变成 $ x $ 的左孩子,如下图
![](https://cdn.luogu.com.cn/upload/image_hosting/3j6zaz0z.png)
![](https://cdn.luogu.com.cn/upload/image_hosting/1noqmgdt.png)
### 01.03 插入
先执行二叉搜索树的插入,判断是否失衡( $ F \notin [-1,0, 1] $ )
>当 $|F|>1$ 发生失衡,根据**当前节点**和**它的失衡子节点**的平衡因子,分为4类。

* LL型:
  当前节点 $F>1$(左子树过高),左儿子的 $F\ge0$。
  >现象:左子树的左子树过重。
  >处理:对当前节点执行 **zig(右旋)**。
  >
![](https://cdn.luogu.com.cn/upload/image_hosting/r2kqfloq.png)
![](https://cdn.luogu.com.cn/upload/image_hosting/d32x0zn7.png)

* LR型:
  当前节点 $F>1$(左子树过高),左儿子的 $F<0$。
  >现象:左子树的右子树过重,呈“先左拐”形态。
  >处理:先对左儿子执行 **zag(左旋)**(变为LL),再对当前节点执行 **zig(右旋)**。

![](https://cdn.luogu.com.cn/upload/image_hosting/zciq75rk.png)
![](https://cdn.luogu.com.cn/upload/image_hosting/azf35kt0.png)
![](https://cdn.luogu.com.cn/upload/image_hosting/czjnzb49.png)

* RR型:
  当前节点 $F<-1$(右子树过高),右儿子的 $F\le0$。
  >现象:右子树的右子树过重。
  >处理:对当前节点执行 **zag(左旋)**。

![](https://cdn.luogu.com.cn/upload/image_hosting/usuyi8qj.png)
![](https://cdn.luogu.com.cn/upload/image_hosting/lib2hy48.png)

* RL型:
  当前节点 $F<-1$(右子树过高),右儿子的 $F>0$。
  >现象:右子树的左子树过重,呈“先右拐”形态。
  >处理:先对右儿子执行 **zig(右旋)**,再对当前节点执行 **zag(左旋)**。

![](https://cdn.luogu.com.cn/upload/image_hosting/5fvez2nq.png)
![](https://cdn.luogu.com.cn/upload/image_hosting/njxbcj3o.png)
![](https://cdn.luogu.com.cn/upload/image_hosting/j6yj4zi7.png)

口诀:正  $ L $ 负  $ R $

### 01.04 删除
先执行二叉搜索树删除,修复逻辑与插入复用一套 `avlfix()`,不同点在于可能影响多层,递归的每一层都要`avlfix()`,这里不多赘述

### 01.05 完整封装代码
```cpp
template<typename T>
struct AVL_Node {
    T val;
    int cnt;
    int siz;
    int h;
    AVL_Node<T> *lson, *rson;
    AVL_Node(T v = T()) : val(v), cnt(1), siz(1), h(1), lson(nullptr), rson(nullptr) {}
};

template<typename T>
void maintain(AVL_Node<T>*& root) {
    if (root == nullptr) return;
    int ls_siz = root->lson ? root->lson->siz : 0;
    int rs_siz = root->rson ? root->rson->siz : 0;
    root->siz = ls_siz + rs_siz + root->cnt;

    int lh = root->lson ? root->lson->h : 0;
    int rh = root->rson ? root->rson->h : 0;
    root->h = (lh > rh ? lh : rh) + 1;
}

template<typename T>
int bal_factor(AVL_Node<T>* root) {
    if (!root) return 0;
    int lh = root->lson ? root->lson->h : 0;
    int rh = root->rson ? root->rson->h : 0;
    return lh - rh;
}

template<typename T>
void zig(AVL_Node<T>*& x) {
    AVL_Node<T>* l = x->lson;
    x->lson = l->rson;
    l->rson = x;

    maintain(x);
    maintain(l);
    x = l;
}

template<typename T>
void zag(AVL_Node<T>*& x) {
    AVL_Node<T>* r = x->rson;
    x->rson = r->lson;
    r->lson = x;

    maintain(x);
    maintain(r);
    x = r;
}

template<typename T>
void avl_fix(AVL_Node<T>*& root) {
    if (!root) return;
    int F = bal_factor(root);
    // LL
    if (F > 1 && bal_factor(root->lson) >= 0) {
        zig(root);
    }
    // LR
    else if (F > 1 && bal_factor(root->lson) < 0) {
        zag(root->lson);
        zig(root);
    }
    // RR
    else if (F < -1 && bal_factor(root->rson) <= 0) {
        zag(root);
    }
    // RL
    else if (F < -1 && bal_factor(root->rson) > 0) {
        zig(root->rson);
        zag(root);
    }
    maintain(root);
}

template<typename T>
bool find(AVL_Node<T>* root, T x) {
    if (root == nullptr) return false;
    if (x < root->val) return find(root->lson, x);
    if (x > root->val) return find(root->rson, x);
    return true;
}

template<typename T>
void insert(AVL_Node<T>*& root, T x) {
    if (root == nullptr) {
        root = new AVL_Node<T>(x);
        return;
    }
    if (x < root->val) insert(root->lson, x);
    else if (x > root->val) insert(root->rson, x);
    else root->cnt ++;

    maintain(root);
    avl_fix(root);
}

template<typename T>
AVL_Node<T>*& getMax(AVL_Node<T>*& root) {
    if (root->rson == nullptr) return root;
    auto &res = getMax(root->rson);
    maintain(root);
    return res;
}

template<typename T>
void remove(AVL_Node<T>*& root, T x) {
    if (root == nullptr) return;
    if (x < root->val) remove(root->lson, x);
    else if (x > root->val) remove(root->rson, x);
    else {
        if (root->cnt > 1) {
            root->cnt --;
        } else {
            if (root->lson == nullptr && root->rson == nullptr) {
                delete root;
                root = nullptr;
            } else if (root->lson == nullptr) {
                auto tmp = root;
                root = root->rson;
                delete tmp;
            } else if (root->rson == nullptr) {
                auto tmp = root;
                root = root->lson;
                delete tmp;
            } else {
                auto &max_node = getMax(root->lson);
                root->val = max_node->val;
                root->cnt = max_node->cnt;
                max_node->cnt = 1;
                remove(max_node, max_node->val);
            }
        }
    }
    maintain(root);
    avl_fix(root);
}

template<typename T>
int get_rank(AVL_Node<T>* root, T x) {
    if (root == nullptr) return 0;
    int ls_siz = root->lson ? root->lson->siz : 0;
    if (x <= root->val) {
        return get_rank(root->lson, x);
    } else {
        return ls_siz + root->cnt + get_rank(root->rson, x);
    }
}

template<typename T>
T kth(AVL_Node<T>* root, int k) {
    int ls_siz = root->lson ? root->lson->siz : 0;
    if (k <= ls_siz) {
        return kth(root->lson, k);
    } else if (k <= ls_siz + root->cnt) {
        return root->val;
    } else {
        return kth(root->rson, k - ls_siz - root->cnt);
    }
}

template<typename T>
T get_pre(AVL_Node<T>* root, T x) {
    T res = -(1 << 31);
    auto p = root;
    while (p != nullptr) {
        if (p->val < x) {
            res = p->val;
            p = p->rson;
        } else {
            p = p->lson;
        }
    }
    return res;
}

template<typename T>
T get_suc(AVL_Node<T>* root, T x) {
    T res = 1 << 31;
    auto p = root;
    while (p != nullptr) {
        if (p->val > x) {
            res = p->val;
            p = p->lson;
        } else {
            p = p->rson;
        }
    }
    return res;
}

AC代码

int main() {
    AVL_Node<int>* rt = nullptr;
    int n;
    cin >> n;
    while(n--) {
        int op, x;
        cin >> op >> x;
        if(op == 1) insert(rt, x);
        else if(op == 2) remove(rt, x);
        else if(op == 3) cout << get_rank(rt, x) + 1 << '\n';
        else if(op == 4) cout << kth(rt, x) << '\n';
        else if(op == 5) cout << get_pre(rt, x) << '\n';
        else if(op == 6) cout << get_suc(rt, x) << '\n';
    }
    return 0;
}