I know there are already multiple question on this topics, but none of them has the solution to my problem.
I'm trying to build a Search Tree that has two options:
build the tree
get from the user a tree and search in it (eg as list, dictionary, ...)
My problem is with the second option, as it appears to be an AttributeError
.
When I run my code with no given tree it works fine, but when I try it with a list an error message appears:
self.root.add(i)
AttributeError: 'NoneType' object has no attribute 'add'
My code:
import unittest
class Testfunction(unittest.TestCase):
def test(self):
init = SearchTree(['x', 'b', 'eee'])
init.add('left')
init.add('right')
init.tolist()
self.assertEqual(init.__contains__('left'),True )
self.assertEqual(init.add('xx'), None )
class Node:
def __init__(self, val):
self.value = val
self.left = None
self.right = None
def insert(self, item):
if self.value == item:
return False
elif self.value > item:
if self.left:
return self.left.insert(item)
else:
self.right = Node(item)
return True
def find(self, item):
if self.value == item:
return True
elif self.value > item:
if self.left:
return self.left.find(item)
else:
return False
else:
if self.right:
return self.right.find(item)
else:
return False
def tolist(self):
if self:
if self.left:
self.left.tolist()
if self.right:
self.right.tolist()
class SearchTree:
def __init__(self, items=None):
# if items . then should be inserted
self.items = items
self.root = None
if items:
for i in self.items:
self.root.add(i)
def __contains__(self, item):
if self.root:
return self.root.find(item)
else:
return False
def add(self, item):
if self.root:
return self.root.insert(item)
else:
self.root = Node(item)
def tolist(self):
self.root.tolist()
test = Testfunction()
test.test()
When you check the items, modify the line to use your built add.
if items:
for i in self.items:
# Instead of self.root.add(i)
self.add(i)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.