I have created a BST using Python and am having issues with the insert function. I can insert one value, but then when I try to insert again it does not work properly. In particular, I get an error on the _insert function that there is no data attribute for a Nonetype object, although the object should be the created root. Here is my implementation:
class Node:
def __init__(self, data, left=None, right=None):
self.data=data
self.left=left
self.right=right
def setdata(self,data):
self.data=data
def hasLeft(self):
return self.left
def hasRight(self):
return self.right
class BST():
def __init__(self):
self.root=None
def insert(self, data):
if self.root:
self._insert(data, self.root)
else:
self.root=Node(data)
def _insert(self, data, curr):
if data<curr.data:
if curr.hasLeft:
self._insert(data, curr.left)
else:
curr.left=Node(data)
if data>curr.data:
if curr.hasRight:
self._insert(data, curr.right)
else:
curr.right=Node(data)
tree=BST()
print tree.root
tree.insert(1)
print tree.root.data
tree.insert(3) # error occurs here
print tree.root.data
Traceback:
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
tree.insert(3)
File "<pyshell#3>", line 6, in insert
self._insert(data, self.root)
File "<pyshell#3>", line 18, in _insert
self._insert(data, curr.right)
File "<pyshell#3>", line 11, in _insert
if data<curr.data:
AttributeError: 'NoneType' object has no attribute 'data'