I want to create an object, lets call it a model, which includes an attribute, the root of a binary tree. I want that model object to have a method which builds a binary tree of a specific depth.
I created such a class, model, which uses a tree node class binary_tree_node, both shown below:
class binary_tree_node:
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
class model:
def __init__(self, max_depth = 3):
self.root = None
self.max_depth = max_depth
def build_tree(self):
self.build_tree_recursive_helper(self.root, 0)
def build_tree_recursive_helper(self, node, current_depth):
# create the new node
node = binary_tree_node('data')
# check base case
if current_depth >= self.max_depth:
return
# make recursive calls
self.build_tree_recursive_helper(node.left_child, current_depth + 1)
self.build_tree_recursive_helper(node.right_child, current_depth + 1)
I expect to be able to instantiate the model, build the tree, then introspect the tree, like so
m = model()
m.build_tree()
print(m.root.data)
>>> 'data'
But instead I get the following upon trying to introspect:
m = model()
m.build_tree()
print(m.root.data)
AttributeError Traceback (most recent call last)
<ipython-input-138-eaa2b3c07e85> in <module>
1 m = model()
2 m.build_tree()
----> 3 print(m.root.data)
AttributeError: 'NoneType' object has no attribute 'data'
This violates my understanding that python passes object references and not values.
How should I modify my binary_tree_node and model classes to achieve my intended results?
nodeand then recursively populating that node's children, it recursively creates a node + children and returns it, and then you assign that return value toself.root.build_treemethod does nothing to the nodes it builds, they are simply discarded.&to signify such a parameter,def Foo(&x): x = 42; a = 0; Foo(a); print(a)would print 42.