I'm trying to write a custom binary tree class. I already have the node:
class Node:
def __init__(self, value, **kwargs):
self.value = value
self.kwargs = kwargs
for key, value in kwargs.items():
setattr(self, key, value)
def __str__(self):
main_str = '{value: ' + str(self.value)
for key, value in self.kwargs.items():
main_str += ', ' + str(key) + ': ' + str(value)
main_str += '}'
return main_str
The node uses kwargs because i'm using it also for other things. The problem i'm having is in the tree class:
from models.node import Node
class BinarySearchTree:
def __init__(self):
self.root = None
def add_element(self, value):
node = Node(value, left=None, right=None)
if not self.root:
self.root = node
else:
self.__add_element_recursive(self.root, value)
def __add_element_recursive(self, parent, value):
if not parent:
node = Node(value, left=None, right=None)
parent = node
elif value > parent.value:
self.__add_element_recursive(parent.right, value)
else:
self.__add_element_recursive(parent.left, value)
This clearly doesn't work because the parameters in python don't get passed as references but as new instances. For example, I know this would work in C++ because I can just pass pointers to the methods.
How do I create the method to add a value to the tree? I think I might be missing something really obvious here.
This clearly doesn't work because the parameters in python don't get passed as references but as new instances.If you pass aNodeinstance as a parameter, the function will receive a reference to that Node not a copy or new instance..