def __recursive_remove(self, value, root):
# the method returns the node with smallest value in a specific tree
def min_val_node(node):
while node.left_child is not None:
node = node.left_child
return node
# Base case
if root is None:
return root
# Search for the node to remove
# go left if the the node value is greater than input value
elif root.value > value:
root.left_child = self.__recursive_remove(value, root.left_child)
#go right if the node value is less than input value
elif root.value < value:
root.right_child = self.__recursive_remove(value, root.right_child)
# delete node if root.value == value
elif root.value == value:
if root.left_child is None and root.right_child is None:
return None
elif root.left_child is None:
return root.right_child
elif root.right_child is None:
return root.left_child
node = min_val_node(root.right_child)
root.value = node.value
root.right_child = self.__recursive_remove(root.value, root.right_child)
return root
def remove_element(self, value):
return self.__recursive_remove(value, self.__root)
我的删除方法在大多数情况下都可以正常工作,除非我尝试删除根节点并且我无法弄清楚问题出在哪里。似乎我的递归删除方法无法更改根节点的值,但代码确实将根值更改为右子树中的最小值。为我的垃圾格式道歉,第一次在 StackOverflow 上发帖 :)