如果我想在一个bst树中插入一个节点再删除一个节点节点仍然维持bst,怎么写代码
时间: 2024-11-25 12:19:01 浏览: 15
在二叉搜索树(BST)中,插入和删除操作需要保持其特性:对于每个节点,左子树的所有节点值小于该节点,右子树的所有节点值大于该节点。这里我会提供一个简单的Python代码示例,演示如何插入和删除节点同时维护BST性质:
**插入节点:**
```python
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
else:
node.right = insert(node.right, key)
return node
```
**删除节点(考虑了三种情况:键不存在、只有一个子节点和有两个子节点):**
```python
def delete_node(root, key):
if root is None:
return root
# Case 1: Key not found
if key < root.key:
root.left = delete_node(root.left, key)
elif key > root.key:
root.right = delete_node(root.right, key)
else:
# Case 2: Leaf node or one child
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
# Case 3: Two children
temp = find_min_value_node(root.right) # Find the minimum in right subtree
root.key = temp.key # Replace with minimum's value
root.right = delete_node(root.right, temp.key)
return root
def find_min_value_node(node):
current = node
while current.left is not None:
current = current.left
return current
```
这个代码实现了插入和删除操作,并通过递归的方式维护BST结构。删除过程中需要找到合适的替代节点(最小值替换或空位移除),以保证删除后的BST属性。
阅读全文