I'm trying to teach myself Python, coming from C++, so I decided to try and build a simple BST. I managed to get my insert method working correctly, but I do not know why my printTree method fails. The interpreter gives me the error:
Traceback (most recent call last): File "test.py", line 40, in myTree.printTree() File "test.py", line 23, in printTree printTree(self.left) NameError: global name 'printTree' is not defined
code:
class Node(object):
def __init__(self, value):
self.value = value
self.left = self.right = None
def insert(self, node):
if self is None:
self = node
else:
if node.value <= self.value:
if self.left: insert(self.left, node)
else: self.left = node
else:
if self.right: insert(self.right, node)
else: self.right = node
def printTree(self):
if not self:
return
else:
printTree(self.left)
print(self.value)
printTree(self.right)
if __name__ == "__main__":
myTree = Node(3)
myTree.insert(Node(2))
myTree.insert(Node(4))
myTree.printTree()
Can I not pass the current instance this way?
insertand your reference torootin printTree.rootwas a typo (fixed). Myinsertfunction seems to work when I write theprintTreefunction explicitlyprintTree(root)and thenprintTree(myTree), which is why I'm confused.