以下是一个示例代码,实现了一个阿尔巴特罗斯二叉搜索树(Albatross Binary Search Tree)的数据结构和相关操作。
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class AlbatrossBST:
def __init__(self):
self.root = None
def insert(self, key):
if self.root is None:
self.root = Node(key)
else:
self._insert_recursive(self.root, key)
def _insert_recursive(self, node, key):
if key < node.key:
if node.left is None:
node.left = Node(key)
else:
self._insert_recursive(node.left, key)
elif key > node.key:
if node.right is None:
node.right = Node(key)
else:
self._insert_recursive(node.right, key)
def search(self, key):
return self._search_recursive(self.root, key)
def _search_recursive(self, node, key):
if node is None or node.key == key:
return node
if key < node.key:
return self._search_recursive(node.left, key)
return self._search_recursive(node.right, key)
def delete(self, key):
self.root = self._delete_recursive(self.root, key)
def _delete_recursive(self, root, key):
if root is None:
return root
if key < root.key:
root.left = self._delete_recursive(root.left, key)
elif key > root.key:
root.right = self._delete_recursive(root.right, key)
else:
if root.left is None:
return root.right
elif root.right is None:
return root.left
root.key = self._min_value(root.right)
root.right = self._delete_recursive(root.right, root.key)
return root
def _min_value(self, node):
current = node
while current.left is not None:
current = current.left
return current.key
def inorder_traversal(self):
self._inorder_recursive(self.root)
def _inorder_recursive(self, node):
if node is not None:
self._inorder_recursive(node.left)
print(node.key)
self._inorder_recursive(node.right)
该示例代码实现了一个基本的阿尔巴特罗斯二叉搜索树,并提供了插入、搜索、删除和中序遍历等常见操作。你可以根据需要进行修改和扩展。