I was trying to construct a Binary Search Tree in python. This is my node class:
class BSTNode:
def __init__(self,val):
self.left = None
self.right = None
self.val = val
This class contains a function called printTree
, which is supposed to print the tree inorder. Here is the printTree function:
def printTree(self,val):
if self.left is not None:
self.left.printTree()
print(self.val)
if self.right is not None:
self.right.printTree()
When I execute the function it gives AttributeError: type object 'BSTNode' has no attribute 'left'
Here is my full code:
class BSTNode:
def __init__(self,val):
self.left = None
self.right = None
self.val = val
def insertNode(self,val):
if self.val:
if val < self.val:
if self.left is None:
self.left = BSTNode(val)
else:
self.left.insertNode(val)
else:
if self.right is None:
self.right = BSTNode(val)
else:
self.right.insertNode(val)
else:
self.val = val
def findval(self,fval):
if (fval == self.val):
print(str(self.val)," data found ")
elif(fval < self.val):
if self.left is None:
print(str(self.val)," data not found")
else:
self.left.findval(fval)
else:
if self.right is None:
print(str(self.val)," data not found")
else:
self.right.findval(fval)
def printTree(self,val):
if self.left is not None:
self.left.printTree()
print(self.val)
if self.right is not None:
self.right.printTree()
root = BSTNode(12)
root.insertNode(6)
root.insertNode(5)
root.insertNode(18)
root.insertNode(15)
root.insertNode(21)
BSTNode.printTree(BSTNode)
printTree()
without arguments:self.left.printTree()
...
self.right.printTree()
Yet, you defined it to accept val
, which is just unused by the way:
def printTree(self,val):
Replace it to:
def printTree(self):
printTree()
is an instance method, not a @classmethod
nor @staticmethod
. That means it requires an active instance/object of BSTNode
to be called which will be passed as the self
argument. So this call is incorrect:BSTNode.printTree(BSTNode)
It must be:
root.printTree(BSTNode)
Then considering my point-1 above, finally it should be:
root.printTree()
Where root
is your current active instance of type BSTNode
.
After those fixes, it would be successful
5
6
12
15
18
21
If you don't want printTree()
to be an instance method, make it a @staticmethod
instead.
class BSTNode:
...
@staticmethod
def printTree(self): # I named it self to be close to your real implementation. Ideally, rename it to something like "node" or "obj" to avoid confusion since this is not an instance method.
if self.left is not None:
self.printTree(self.left)
print(self.val)
if self.right is not None:
self.printTree(self.right)
...
BSTNode.printTree(root)
This will produce the same output.