python实现二叉搜索树
时间: 2024-01-10 08:04:54 浏览: 82
以下是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
curr = self.root
while curr:
if val < curr.val:
if not curr.left:
curr.left = TreeNode(val)
return
curr = curr.left
else:
if not curr.right:
curr.right = TreeNode(val)
return
curr = curr.right
def search(self, val):
curr = self.root
while curr:
if curr.val == val:
return True
elif curr.val > val:
curr = curr.left
else:
curr = curr.right
return False
def delete(self, val):
def find_min(node):
while node.left:
node = node.left
return node
def delete_node(node, val):
if not node:
return None
if node.val == val:
if not node.left and not node.right:
return None
if not node.left:
return node.right
if not node.right:
return node.left
min_node = find_min(node.right)
node.val = min_node.val
node.right = delete_node(node.right, min_node.val)
elif node.val > val:
node.left = delete_node(node.left, val)
else:
node.right = delete_node(node.right, val)
return node
self.root = delete_node(self.root, val)
```
以上代码实现了二叉搜索树的插入、查找和删除操作。其中,插入操作按照二叉搜索树的规则插入节点,查找操作也是按照二叉搜索树的规则进行查找,删除操作则需要考虑三种情况:被删除节点没有子节点、被删除节点只有一个子节点、被删除节点有两个子节点。
阅读全文