用python写一个二叉搜索树算法
时间: 2024-05-08 11:16:50 浏览: 27
下面是Python实现的二叉搜索树算法:
```python
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class BST:
def __init__(self):
self.root = None
def insert(self, value):
node = Node(value)
if self.root is None:
self.root = node
else:
current = self.root
while True:
if value < current.value:
if current.left is None:
current.left = node
break
else:
current = current.left
elif value > current.value:
if current.right is None:
current.right = node
break
else:
current = current.right
def search(self, value):
current = self.root
while current is not None:
if current.value == value:
return True
elif current.value > value:
current = current.left
else:
current = current.right
return False
def inorder(self, node):
if node is not None:
self.inorder(node.left)
print(node.value)
self.inorder(node.right)
def preorder(self, node):
if node is not None:
print(node.value)
self.preorder(node.left)
self.preorder(node.right)
def postorder(self, node):
if node is not None:
self.postorder(node.left)
self.postorder(node.right)
print(node.value)
```
示例用法:
```python
bst = BST()
bst.insert(5)
bst.insert(3)
bst.insert(7)
bst.insert(1)
bst.insert(9)
print(bst.search(7)) # True
print(bst.search(10)) # False
bst.inorder(bst.root) # 1 3 5 7 9
bst.preorder(bst.root) # 5 3 1 7 9
bst.postorder(bst.root) # 1 3 9 7 5
```