定义
搜索二叉树(Binary Search Tree, BST)是一种二叉树,满足以下性质:
- 每个节点都包含一个值。
- 对于树中任意节点:
- 其左子树中所有节点的值小于该节点的值。
- 其右子树中所有节点的值大于该节点的值。
- 左右子树都必须是二叉搜索树。
基本操作
插入操作
插入操作将一个新的值插入到搜索二叉树中的正确位置,以保持搜索二叉树的有序性质。
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert(root, val):
if root is None:
return TreeNode(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
查找操作
查找操作根据给定的值在搜索二叉树中查找节点。
def search(root, val):
if root is None or root.val == val:
return root
if val < root.val:
return search(root.left, val)
else:
return search(root.right, val)
删除操作
删除操作根据给定的值从搜索二叉树中删除节点,并保持其有序性质。
(删除是四个操作中最困难的)
def delete(root, val):
if root is None:
return root
if val < root.val:
root.left = delete(root.left, val)
elif val > root.val:
root.right = delete(root.right, val)
else:
# Case 1: No child or only one child
if root.left is None:
return root.right
elif root.right is None:
return root.left
# Case 2: Two children
successor = find_min(root.right)
root.val = successor.val
root.right = delete(root.right, successor.val)
return root
def find_min(node):
current = node
while current.left is not None:
current = current.left
return current
修改(更新)操作
更新操作通常指的是修改搜索二叉树中节点的值,但保持其结构不变。这里提供一个简单的更新值的例子:
def update(root, target_val, new_val):
node = search(root, target_val)
if node:
node.val = new_val
return root
总结
搜索二叉树是一种重要的数据结构,它支持高效的插入、查找和删除操作(在平均情况下为 O(log n)),并被广泛应用于数据库系统、算法实现等领域。以上是基本的定义和操作示例,希望能帮助大家更深入地理解和实现搜索二叉树。