Python 数据结构入门 - 二叉搜索树(Binary Search Tree)
bst = BinarySearchTree()
for num in (7, 5, 9, 8, 15, 16, 18, 17):
bst.insert(num)
max_node = bst.find_max()
min_node = bst.find_min()
print(f"Max node: {max_node.data}")
print(f"Min node: {min_node.data}")
bst2 = BinarySearchTree()
for num in (7, 5, 9, 8, 15, 16, 18, 17):
bst2.insert(num)
for n in (17, 3, -2, 8, 5):
if bst2.search(n) is not None:
print(f"{n} found in the binary search tree! :D")
else:
print(f"{n} not found in the tree! :(")
bst3 = BinarySearchTree()
for num in (7, 5, 9, 8, 15, 16, 18, 17):
bst3.insert(num)
print('二叉排序树中数据为:')
mid_traverse(bst2.root)
# 删除没有孩子的结点
bst3.delete(5)
# 删除只有一个孩子的结点
bst3.delete(15)
# 删除有两个孩子的结点
bst3.delete(9)
# 查看中序遍历结果
print('\n删除后,二叉排序树中数据为:')
mid_traverse(bst2.root)
用户评论