I'm beginner in Python and I tried to create a function to delete a node in a binary search tree.
I tried calling .delete on a node. The node is a leaf node with no children so it should be deleted. However, after I called .delete, the node is still there.
This is the code:
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
#some functions for insert etc.
def delete(self, key):
"""DELETE"""
try:
if self is None:
print("Tree is empty.")
return None
else:
if key < self.val:
self.left.delete(key)
elif key > self.val:
self.right.delete(key)
else:
#this seems to be the problem
if self.left is None :
temp = self.right
#print(self, self.val, self.right)
self = temp
return
elif self.right is None :
temp = self.left
self = temp
return
temp = minValue(self.right)
self.val = temp.val
self.right.delete(temp.val)
except(AttributeError):
print("There's no such number in a tree.")
def inorder(root):
if root is not None:
inorder(root.left)
print(root.val, end=" ")
inorder(root.right)
def minValue(node):
current = node
while(current.left is not None):
current = current.left
return current
r = Node(50)
After inserting numbers 30 20 40 70 60 80 to r and calling inorder(r) I get: 20 30 40 50 60 70 80, which corresponds to the tree
50
/ \
30 70
/ \ / \
20 40 60 80
but after r.delete(30), I get: 20 40 40 50 60 70 80, which is:
50
/ \
40 70
/ \ / \
20 40 60 80
The value to delete is replaced correctly but the used node (40) without children should be deleted.
What may be the reason of such a problem?