请给出Treap的完整代码
时间: 2023-02-07 13:01:56 浏览: 87
很高兴为您提供 Treap 的完整代码。
Treap 是一种随机化的二叉搜索树,它同时具有二叉搜索树的单调性以及堆的性质。这是一种常用的数据结构,用于存储有序的数据。
下面是 Treap 的完整代码,使用 Python 语言编写:
```
import random
class Node:
def __init__(self, key, priority):
self.key = key
self.priority = priority
self.left = None
self.right = None
class Treap:
def __init__(self):
self.root = None
def insert(self, key):
new_node = Node(key, random.random())
self.root = self._insert(self.root, new_node)
def _insert(self, root, new_node):
if not root:
return new_node
if new_node.key < root.key:
root.left = self._insert(root.left, new_node)
if root.left.priority > root.priority:
root = self._rotate_right(root)
else:
root.right = self._insert(root.right, new_node)
if root.right.priority > root.priority:
root = self._rotate_left(root)
return root
def delete(self, key):
self.root = self._delete(self.root, key)
def _delete(self, root, key):
if not root:
return root
if key < root.key:
root.left = self._delete(root.left, key)
elif key > root.key:
root.right = self._delete(root.right, key)
else:
if not root.left and not root.right:
root = None
elif not root.left:
root = root.right
elif not root.right:
root = root.left
elif root.left.priority > root.right.priority:
root = self._rotate_right(root)
root.right = self._delete(root.right, key)
else:
root = self._rotate_left(root)
root.left = self._delete(root.left, key)
return root
def search(self, key):
return self._search(self.root, key)
def _search(self, root, key):
if not root or root.key == key:
return root
if key < root.key:
return self._search(root.left, key)
else:
return self._search(root.right,
阅读全文