📅  最后修改于: 2023-12-03 14:58:32.177000             🧑  作者: Mango
本题为GATE-CS-2017(套装2)第47题。题目考察了对二叉搜索树的基本操作,包括删除节点、查找最小值、查找最大值、查找某个键值、插入节点等。
给定一个二叉搜索树,实现以下几个函数:
delete_node(root, key)
:删除二叉搜索树中键值为key的节点;search_min(node)
:查找并返回以node为根节点二叉搜索树中的最小值节点;search_max(node)
:查找并返回以node为根节点二叉搜索树中的最大值节点;search_node(node, key)
:查找并返回以node为根节点二叉搜索树中键值为key的节点;insert_node(node, key)
:以node为根节点插入键值为key的节点。class Node:
def __init__(self, key):
self.left = None
self.right = None
self.key = key
def delete_node(root, key):
if root is None:
return root
if key < root.key:
root.left = delete_node(root.left, key)
return root
elif key > root.key:
root.right = delete_node(root.right, key)
return root
else:
if root.left is None and root.right is None:
root = None
return root
elif root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
else:
temp = search_min(root.right)
root.key = temp.key
root.right = delete_node(root.right, temp.key)
return root
def search_min(node):
current = node
while(current.left is not None):
current = current.left
return current
def search_max(node):
current = node
while(current.right is not None):
current = current.right
return current
def search_node(node, key):
if node is None or node.key == key:
return node
if node.key < key:
return search_node(node.right, key)
return search_node(node.left, key)
def insert_node(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert_node(node.left, key)
elif key > node.key:
node.right = insert_node(node.right, key)
return node
delete_node(root, key)
:时间复杂度为O(h),其中h为树的高度search_min(node)
:时间复杂度为O(h),其中h为树的高度search_max(node)
:时间复杂度为O(h),其中h为树的高度search_node(node, key)
:时间复杂度为O(h),其中h为树的高度insert_node(node, key)
:时间复杂度为O(h),其中h为树的高度