2.首先编程实现读入一串字符创建一棵二叉排序树,然后分别实现:二叉排序树的查找;二叉排序树的插入;二叉排序树的删除等操作。
时间: 2023-10-16 18:24:52 浏览: 67
以下是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)
else:
self._insert(self.root, val)
def _insert(self, node, val):
if val < node.val:
if not node.left:
node.left = TreeNode(val)
else:
self._insert(node.left, val)
else:
if not node.right:
node.right = TreeNode(val)
else:
self._insert(node.right, val)
# 查找节点
def search(self, val):
return self._search(self.root, val)
def _search(self, node, val):
if not node:
return False
if node.val == val:
return True
elif val < node.val:
return self._search(node.left, val)
else:
return self._search(node.right, val)
# 删除节点
def delete(self, val):
self._delete(None, self.root, val)
def _delete(self, parent, node, val):
if not node:
return
if node.val == val:
if not node.left and not node.right:
if not parent:
self.root = None
elif parent.left == node:
parent.left = None
else:
parent.right = None
elif not node.left:
if not parent:
self.root = node.right
elif parent.left == node:
parent.left = node.right
else:
parent.right = node.right
elif not node.right:
if not parent:
self.root = node.left
elif parent.left == node:
parent.left = node.left
else:
parent.right = node.left
else:
min_node = self._find_min(node.right)
node.val = min_node.val
self._delete(node, node.right, min_node.val)
elif val < node.val:
self._delete(node, node.left, val)
else:
self._delete(node, node.right, val)
def _find_min(self, node):
while node.left:
node = node.left
return node
```
使用示例:
```
bst = BST()
bst.insert(5)
bst.insert(3)
bst.insert(7)
bst.insert(1)
bst.insert(4)
bst.insert(6)
bst.insert(8)
print(bst.search(6)) # True
bst.delete(6)
print(bst.search(6)) # False
```
阅读全文