设计并实现二叉排序树类,包含插入、创建、查找、遍历算法,将任意一个无序数据序列转换为一棵二叉排序树,并中序遍历后输出有序数据
时间: 2023-06-27 09:06:34 浏览: 91
二叉树的基本操作,包括前序、中序、后序遍历的递归和非递归算法
5星 · 资源好评率100%
好的,下面是我为你提供的二叉排序树类的实现代码:
```python
class BSTNode:
def __init__(self, key=None, val=None):
self.key = key
self.val = val
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert(self, key, val):
if self.root is None:
self.root = BSTNode(key, val)
else:
self._insert(key, val, self.root)
def _insert(self, key, val, cur_node):
if key < cur_node.key:
if cur_node.left is None:
cur_node.left = BSTNode(key, val)
else:
self._insert(key, val, cur_node.left)
elif key > cur_node.key:
if cur_node.right is None:
cur_node.right = BSTNode(key, val)
else:
self._insert(key, val, cur_node.right)
else:
cur_node.val = val
def create(self, data):
for key, val in data.items():
self.insert(key, val)
def search(self, key):
return self._search(key, self.root)
def _search(self, key, cur_node):
if cur_node is None:
return None
elif cur_node.key == key:
return cur_node.val
elif key < cur_node.key:
return self._search(key, cur_node.left)
else:
return self._search(key, cur_node.right)
def inorder_traversal(self):
nodes = []
self._inorder_traversal(self.root, nodes)
return nodes
def _inorder_traversal(self, cur_node, nodes):
if cur_node is not None:
self._inorder_traversal(cur_node.left, nodes)
nodes.append(cur_node.val)
self._inorder_traversal(cur_node.right, nodes)
```
使用方法:
```python
# 创建BST实例
bst = BST()
# 插入元素
bst.insert(5, "apple")
bst.insert(3, "banana")
bst.insert(7, "orange")
bst.insert(2, "pear")
bst.insert(4, "peach")
bst.insert(6, "grape")
bst.insert(8, "watermelon")
# 遍历BST
print(bst.inorder_traversal()) # ['pear', 'banana', 'peach', 'apple', 'grape', 'orange', 'watermelon']
# 查找元素
print(bst.search(3)) # 'banana'
```
将任意一个无序数据序列转换为一棵二叉排序树,并中序遍历后输出有序数据:
```python
data = {"d": 4, "b": 2, "a": 1, "c": 3, "f": 6, "e": 5, "g": 7}
# 创建BST实例
bst = BST()
# 将无序数据序列转换为二叉排序树
bst.create(data)
# 遍历BST
print(bst.inorder_traversal()) # [1, 2, 3, 4, 5, 6, 7]
```
这样,你就可以使用这个二叉排序树类,进行插入、创建、查找、遍历等操作,并将任意一个无序数据序列转换为一棵二叉排序树,并中序遍历后输出有序数据。
阅读全文