OJSF 信息学 Wiki · 第 98 / 144 节 · K086

98 · K086 二叉搜索树与平衡思想

独立过关 · 样例与错因 · 课末题

95 分钟。先掌握按值走分支,再给子树加 size 做排名。最后直观看见「中序仍有序」并不保证搜索快。

1. 先修自查

堆只保证父子间优先级,不能拿中序直接排序。BST 按键要求左子树的所有键小于当前、右子树的所有键大于当前;重复值本节在同一个节点计 cnt。

2. 从比较查找推到排名

查找比当前小就左走,比当前大就右走。中序输出会得到非降序。size=左大小+cnt+右大小,大小统计元素数不是不同键的种数。求严格小于 x 的数:若当前键<x,把左大小加 cnt,再向右;否则向左。第 k 小:若 k≤左大小去左;若在左大小后的 cnt 个名次内,就返回当前键;再否则减掉左大小与 cnt 去右。

代码复杂度按树高 h 说是 O(h),不能先写 O(log n)。按升序插入会产生右链。平衡的目标是控制高度,例如旋转把 3 的左孩子 2 提上来,2 原来的右子树接到 3 左方,键序不变。例如 3 左接 2、2 右接 2.5,旋转后 2 右接 3、3 左接 2.5,中序仍为 2,2.5,3。小数只作图示,下面程序存整数键。下一节 FHQ 用随机优先级和分裂合并,而不是显式旋转。

3. 跟做:重复值占用两个名次

插入 5、3、7、3:中序列 [3,3,5,7]。严格小于 5 的数有 2;第 2 小仍为 3;第 3 小为 5。相同最终键集合按 [3,5,7] 插入会变成链,而 [5,3,7] 是两层。用纸画两棵树,查 7 时比较次数分别 3 与 2。

4. 改一条规则:前驱和后继是严格关系

对 [3,3,5,7],x=3 的前驱不存在,后继是 5,不是另一份 3。可先算 count(<x) 和 count(≤x),再求相邻排名;不用 x−1、x+1 来伪造严格性,以免在整数极限出错。

5. 独立过关:有重复的排名

首行 q≤2000,每行 op x,1 插入 x、2 输出严格小于 x 的个数、3 输出第 x 小,非法名次则输出 NONE。键值为有符号 64 位整数。输入 7 / 1 5 / 1 3 / 1 3 / 2 5 / 3 2 / 3 3 / 3 4,输出 2、3、5、NONE。

6. 提示、程序与错因

展开:数组下标存节点,不依赖递归栈

每次沿一条路径,时间 O(树高),空间 O(q)。查重复键时 size 仍计份数;升序大输入的最坏总用时 O(q²),不把这个版本当成「平衡」。

#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
class BST {
    struct Node {long long key;int l,r,cnt,size;};
    vector<Node> t{{0,0,0,0,0}};
    int root=0;
    int make(long long x) {
        t.push_back({x,0,0,1,1});
        return static_cast<int>(t.size())-1;
    }
public:
    void insert(long long x) {
        if (!root) {root=make(x);return;}
        int u=root;
        while (true) {
            ++t[u].size; // 插入经过的祖先都多一个元素
            if (x==t[u].key) {++t[u].cnt;return;}
            bool left=x<t[u].key;
            int v=left?t[u].l:t[u].r;
            if (v) u=v;
            else {
                int z=make(x); // push_back 可能扩容,不保存 Node 的引用
                if (left) t[u].l=z;else t[u].r=z;
                return;
            }
        }
    }
    int size() const {return t[root].size;}
    int count(long long x,bool equal) const {
        int r=0,u=root;
        while (u) {
            if (t[u].key<x || (equal && t[u].key==x)) {
                r+=t[t[u].l].size+t[u].cnt;u=t[u].r;
            } else u=t[u].l;
        }
        return r; // equal 决定查 <x 还是 <=x
    }
    long long kth(int k) const {
        int u=root;
        while (u) {
            int l=t[t[u].l].size;
            if (k<=l) u=t[u].l;
            else if (k<=l+t[u].cnt) return t[u].key;
            else {k-=l+t[u].cnt;u=t[u].r;} // 跳过左子树和自身重复份数
        }
        return 0; // 调用者保证 k 合法
    }
};
int main() {
    ios::sync_with_stdio(false);cin.tie(nullptr);
    int q;cin>>q;BST t;
    while (q--) {
        int op;long long x;cin>>op>>x;
        if (op==1) t.insert(x);
        else if (op==2) cout<<t.count(x,false)<<'\n';
        else if (x<1 || x>t.size()) cout<<"NONE\n";
        else cout<<t.kth(static_cast<int>(x))<<'\n';
    }
}

7. 经典题解析:洛谷 P5076 普通二叉树(简化版)

q≤10^4,原题是集合(不重复插入),支持排名、第 k 小、前驱、后继、插入。普通 BST 用 size 查,不依赖线性中序遍历。排名为 count(<x)+1,即使集合中没有 x 也一样。前驱取第 count(<x) 小;后继取第 count(≤x)+1 小;无解用题目规定常量,不把这些常量插进树。例依次插 3、7,问 5 的排名 2、前驱 3、后继 7;问 3 的前驱为 −2147483647。单次 O(h),总量最坏 O(q²),正式大规模须使用平衡结构。

#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
class BST {
    struct Node {long long key;int l,r,cnt,size;};
    vector<Node> t{{0,0,0,0,0}};
    int root=0;
    int make(long long x) {
        t.push_back({x,0,0,1,1});
        return static_cast<int>(t.size())-1;
    }
public:
    void insert(long long x) {
        if (!root) {root=make(x);return;}
        int u=root;
        while (true) {
            ++t[u].size; // 插入经过的祖先都多一个元素
            if (x==t[u].key) {++t[u].cnt;return;}
            bool left=x<t[u].key;
            int v=left?t[u].l:t[u].r;
            if (v) u=v;
            else {
                int z=make(x); // push_back 可能扩容,不保存 Node 的引用
                if (left) t[u].l=z;else t[u].r=z;
                return;
            }
        }
    }
    int size() const {return t[root].size;}
    int count(long long x,bool equal) const {
        int r=0,u=root;
        while (u) {
            if (t[u].key<x || (equal && t[u].key==x)) {
                r+=t[t[u].l].size+t[u].cnt;u=t[u].r;
            } else u=t[u].l;
        }
        return r; // equal 决定查 <x 还是 <=x
    }
    long long kth(int k) const {
        int u=root;
        while (u) {
            int l=t[t[u].l].size;
            if (k<=l) u=t[u].l;
            else if (k<=l+t[u].cnt) return t[u].key;
            else {k-=l+t[u].cnt;u=t[u].r;} // 跳过左子树和自身重复份数
        }
        return 0; // 调用者保证 k 合法
    }
};
int main() {
    ios::sync_with_stdio(false);cin.tie(nullptr);
    int q;cin>>q;BST t;
    while (q--) {
        int op;long long x;cin>>op>>x;
        if (op==5) t.insert(x);
        else if (op==1) cout<<t.count(x,false)+1<<'\n';
        else if (op==2) cout<<t.kth(static_cast<int>(x))<<'\n';
        else if (op==3) {
            int k=t.count(x,false);cout<<(k?t.kth(k):-2147483647LL)<<'\n';
        } else {
            int k=t.count(x,true)+1;cout<<(k<=t.size()?t.kth(k):2147483647LL)<<'\n';
        }
    }
}

上一节:树上前缀和与点边差分 · 回到课程目录 · 下一节:FHQ-Treap与分裂合并