class BinarySearchTree:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def insert(self, value) -> bool:
current_node = self
while current_node is not None:
if current_node.value < value:
current_node = current_node.left
elif current_node.value == value:
return False
elif current_node.value > value:
current_node = current_node.right
# id(current_node) <-- I need to create a object on this
current_node = BinarySearchTree(value) # <--
# id(current_node) <-- This is a new assigned id, but I need the same as the previous id
return True
binary_search_tree = BinarySearchTree(2)
binary_search_tree.insert(5)
print(binary_search_tree.__dict__)
current_node refers to current_node.left or current_node.right.
I need to create a new object and assign it to the pointer the current_node is referring,
but I only create a new object and assign it to a new pointer.
After the loop, as Scott Hunter noted,
current_nodeisNone, sothe previous idis the “identity” ofNone, and you surely understand that a new object'sidcannot be the same as theidofNone. What you could do is modify the loop in a way which allows to refer to the attributeleftorrightafterwards as needed:Alternatively you could make things a bit more simple by replacing in
__init__with
and the whole body of
insertwith