python写二叉搜索树
时间: 2023-05-20 08:01:09 浏览: 116
二叉搜索树是一种常见的数据结构,它具有快速查找、插入和删除元素的特点。下面是一个简单的 Python 实现:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert(self, val):
if not self.root:
self.root = TreeNode(val)
return
node = self.root
while node:
if val < node.val:
if not node.left:
node.left = TreeNode(val)
return
node = node.left
else:
if not node.right:
node.right = TreeNode(val)
return
node = node.right
def search(self, val):
node = self.root
while node:
if val == node.val:
return True
elif val < node.val:
node = node.left
else:
node = node.right
return False
def delete(self, val):
def find_min(node):
while node.left:
node = node.left
return node
def delete_node(node, val):
if not node:
return None
if val == node.val:
if not node.left and not node.right:
return None
elif not node.left:
return node.right
elif not node.right:
return node.left
else:
min_node = find_min(node.right)
node.val = min_node.val
node.right = delete_node(node.right, min_node.val)
elif val < node.val:
node.left = delete_node(node.left, val)
else:
node.right = delete_node(node.right, val)
return node
self.root = delete_node(self.root, val)
```
以上是一个简单的二叉搜索树实现,包括插入、查找和删除操作。
阅读全文