首先编程实现读入一串字符创建一棵二叉排序树,然后分别实现:二叉排序树的查找;二叉排序树的插入;二叉排序树的删除等操作。流程图
时间: 2023-11-27 10:48:12 浏览: 89
```flow
st=>start: 开始
op1=>operation: 读入一串字符
op2=>operation: 创建一棵二叉排序树
op3=>operation: 二叉排序树的查找
op4=>operation: 二叉排序树的插入
op5=>operation: 二叉排序树的删除
e=>end: 结束
st->op1->op2->op3->op4->op5->e
```
以下是Python代码实现:
```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)
return
cur = self.root
while cur:
if val < cur.val:
if not cur.left:
cur.left = TreeNode(val)
return
cur = cur.left
else:
if not cur.right:
cur.right = TreeNode(val)
return
cur = cur.right
# 查找节点
def search(self, val):
cur = self.root
while cur:
if val == cur.val:
return True
elif val < cur.val:
cur = cur.left
else:
cur = cur.right
return False
# 删除节点
def delete(self, val):
def find_min(root):
while root.left:
root = root.left
return root
def delete_node(root, val):
if not root:
return None
if val < root.val:
root.left = delete_node(root.left, val)
elif val > root.val:
root.right = delete_node(root.right, val)
else:
if not root.left and not root.right:
root = None
elif not root.left:
root = root.right
elif not root.right:
root = root.left
else:
temp = find_min(root.right)
root.val = temp.val
root.right = delete_node(root.right, temp.val)
return root
self.root = delete_node(self.root, val)
```
阅读全文