I'm trying to implement the delete function of a binary search tree. The logic makes sense to me, but I'm having trouble understanding why my code doesn't seem to work. The difference I found was that returning the changes recursively from the bottom up seems to work, but simply removing the node when found doesn't. Could anyone help shed light on this?
My code (and what makes most sense to me)
def _delete(self, root, value):
if root is None:
return
if value < root.data:
self._delete(root.left, value)
elif value > root.data:
self._delete(root.right, value)
else:
if root.left is not None and root.right is not None:
root.data = self._find_min_value(root.right)
self._delete(root.right, root.data)
elif root.left is not None:
root = root.left
else:
root = root.right
The solution I found
def _delete(self, root, value):
if root is None:
return
if value < root.data:
root.left = self._delete(root.left, value)
elif value > root.data:
root.right = self._delete(root.right, value)
else:
if root.left is not None and root.right is not None:
root.data = self._find_min_value(root.right)
root.right = self._delete(root.right, root.data)
elif root.left is not None:
return root.left
else:
return root.right
return root