17
loading...
This website collects cookies to deliver better user experience
def getSuccessor(currentNode):
while currentNode.left:
currentNode = currentNode.left
return currentNode
def delete(value: int, root):
"""
[code is from] => https://www.geeksforgeeks.org/binary-search-tree-set-2-delete/
"""
# if the tree is empty
if root is None:
return root
# if value is smaller than the root's value
if value < root.value:
root.left = delete(value , root.left)
# if value is greater than the root's value
elif(value > root.value):
root.right = delete(value, root.right)
else:
#! case1 or case2 (node has not children or has only one)
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: node has 2 children
# getting successor
temp = getSuccessor(root.right)
# Copy the successor's value to the node's value
root.value = temp.value
# Delete the successor
root.right = delete(temp.value, root.right)
return root