在计算机科学中,Treap(Tree + Heap 的组合词)是一种结合了二叉搜索树(BST)和堆(Heap)特性的随机化数据结构。它既能像二叉搜索树那样高效地支持查找、插入和删除操作,又能通过随机优先级维持近似平衡的结构,从而避免退化为链表。本教程将手把手教你用 C++ 实现 Treap 树,即使你是编程小白,也能轻松掌握!

Treap 是一种平衡二叉搜索树(Balanced BST),它的每个节点包含两个值:
由于 priority 是随机分配的,Treap 在期望情况下是平衡的,其高度为 O(log n),因此所有操作的时间复杂度均为 O(log n)。
为了同时满足 BST 和 Heap 的性质,Treap 使用左旋(Left Rotate)和右旋(Right Rotate)来调整结构。这是实现插入和删除的关键。
// 右旋:将 y 作为新的根,x 成为其右子Node* rightRotate(Node* y) { Node* x = y->left; Node* T2 = x->right; // 执行旋转 x->right = y; y->left = T2; return x; // 新的根}// 左旋:将 x 作为新的根,y 成为其左子Node* leftRotate(Node* x) { Node* y = x->right; Node* T2 = y->left; // 执行旋转 y->left = x; x->right = T2; return y; // 新的根}首先,我们定义 Treap 的节点结构:
#include <iostream>#include <cstdlib> // 用于 rand()#include <ctime> // 用于 srand(time(0))struct Node { int key; // 键值 int priority; // 随机优先级 Node *left, *right; Node(int k) { key = k; priority = rand(); // 随机生成优先级 left = right = nullptr; }};插入时,先按 BST 规则找到插入位置,然后通过旋转恢复堆性质:
Node* insert(Node* root, int key) { // 1. 执行标准 BST 插入 if (!root) return new Node(key); if (key <= root->key) { root->left = insert(root->left, key); // 如果左子优先级更高,右旋 if (root->left->priority > root->priority) root = rightRotate(root); } else { root->right = insert(root->right, key); // 如果右子优先级更高,左旋 if (root->right->priority > root->priority) root = leftRotate(root); } return root;}#include <iostream>#include <cstdlib>#include <ctime>using namespace std;struct Node { int key, priority; Node *left, *right; Node(int k) : key(k), priority(rand()), left(nullptr), right(nullptr) {}};Node* rightRotate(Node* y) { Node* x = y->left; Node* T2 = x->right; x->right = y; y->left = T2; return x;}Node* leftRotate(Node* x) { Node* y = x->right; Node* T2 = y->left; y->left = x; x->right = T2; return y;}Node* insert(Node* root, int key) { if (!root) return new Node(key); if (key <= root->key) { root->left = insert(root->left, key); if (root->left->priority > root->priority) root = rightRotate(root); } else { root->right = insert(root->right, key); if (root->right->priority > root->priority) root = leftRotate(root); } return root;}void inorder(Node* root) { if (root) { inorder(root->left); cout << "(" << root->key << ", " << root->priority << ") "; inorder(root->right); }}int main() { srand(time(0)); // 初始化随机种子 Node* root = nullptr; root = insert(root, 10); root = insert(root, 20); root = insert(root, 5); root = insert(root, 15); cout << "中序遍历 (key, priority):\n"; inorder(root); cout << endl; return 0;}相比 AVL 树或红黑树,Treap 的实现更简单,且通过随机化保证了期望平衡。它是学习随机化平衡树的理想起点,也是竞赛和面试中的热门数据结构。
本文详细讲解了 C++ Treap树实现 的原理与代码,包括节点定义、旋转操作、插入逻辑,并提供了完整可运行的示例。Treap 是一种优雅而高效的平衡二叉搜索树C++实现方式,特别适合初学者理解平衡树的核心思想。
掌握 Treap 后,你可以进一步探索删除操作、区间查询、分裂与合并等高级功能。希望这篇教程能帮助你轻松入门 Treap 数据结构!
关键词:C++ Treap树实现, Treap数据结构教程, 平衡二叉搜索树C++, 随机化平衡树
本文由主机测评网于2025-12-23发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/20251211926.html