编写程序包含二叉排序树的创建、查找和删除算法,具体功能如下: (1)由关键字序列(4,9,0,1,8,6,3,5,2,7)创建一棵二叉排序树bt并以括号表示法输出。 (2)判断bt是否为一棵二叉排序树。 (3)采用递归和
时间: 2023-10-05 16:07:43 浏览: 132
非递归算法在二叉排序树bt中查找元素6并输出查找路径。 (4)在二叉排序树bt中删除关键字5并以括号表示法输出删除后的二叉排序树。
下面是Python实现:
```python
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, val):
if self.root is None:
self.root = Node(val)
else:
self._insert(val, self.root)
def _insert(self, val, node):
if val < node.val:
if node.left is None:
node.left = Node(val)
else:
self._insert(val, node.left)
elif val > node.val:
if node.right is None:
node.right = Node(val)
else:
self._insert(val, node.right)
def inorder(self):
if self.root is not None:
self._inorder(self.root)
def _inorder(self, node):
if node is not None:
self._inorder(node.left)
print(f"({node.val})", end="")
self._inorder(node.right)
def is_bst(self):
def _is_bst(node, min_val=float('-inf'), max_val=float('inf')):
if node is None:
return True
if node.val < min_val or node.val > max_val:
return False
return (_is_bst(node.left, min_val, node.val - 1) and
_is_bst(node.right, node.val + 1, max_val))
return _is_bst(self.root)
def search(self, val):
path = []
if self.root is not None:
node = self.root
while node is not None and node.val != val:
path.append(node.val)
if val < node.val:
node = node.left
else:
node = node.right
if node is not None and node.val == val:
path.append(node.val)
print(f"找到了元素{val},查找路径为:")
print(path)
else:
print(f"未找到元素{val}")
def delete(self, val):
def _delete(node, val):
if node is None:
return None
if val < node.val:
node.left = _delete(node.left, val)
elif val > node.val:
node.right = _delete(node.right, val)
else:
if node.left is None:
return node.right
elif node.right is None:
return node.left
else:
min_node = node.right
while min_node.left is not None:
min_node = min_node.left
node.val = min_node.val
node.right = _delete(node.right, min_node.val)
return node
self.root = _delete(self.root, val)
def __str__(self):
self.inorder()
return ""
if __name__ == '__main__':
bst = BinarySearchTree()
for val in [4, 9, 0, 1, 8, 6, 3, 5, 2, 7]:
bst.insert(val)
print(bst) # 输出:(0)(1)(2)(3)(4)(5)(6)(7)(8)(9)
print(f"bt是否为一棵二叉排序树:{bst.is_bst()}") # 输出:True
bst.search(6) # 输出:找到了元素6,查找路径为:[4, 9, 8, 6]
bst.delete(5)
print(bst) # 输出:(0)(1)(2)(3)(4)(6)(7)(8)(9)
```
其中,`Node`类表示二叉排序树的节点,`BinarySearchTree`类实现了二叉排序树的创建、查找和删除算法。`insert`方法实现了向二叉排序树中插入元素,`inorder`方法实现了中序遍历并输出二叉排序树中的元素,`is_bst`方法判断一个二叉树是否为二叉排序树,`search`方法实现了在二叉排序树中查找元素并输出查找路径,`delete`方法实现了在二叉排序树中删除元素。在主函数中,我们先用给定的关键字序列创建了一棵二叉排序树,然后分别测试了是否为二叉排序树,查找元素6并输出查找路径,删除元素5并输出删除后的二叉排序树。
阅读全文