我在二进制搜索树类中工作,当我运行insert方法时出现此错误:
AttributeError: 'BSearch_tree' object has no attribute 'key'
我不明白我做错了什么,而且我无法弄清楚应该修复什么!
这是我的代码:
class Tree_node():
def __init__(self, key, val):
self.key = key
self.val = val
self.left = None
self.right = None
class BSearch_tree():
def __init__(self):
self.root=None
def insert(self, key, val):
if self.root is None:
self.root=Tree_node(key,val)
elif key == self.root.key:
self.val=val
elif key < self.root.key:
left = BSearch_tree()
left.root = self.root.left
self.root.left=BSearch_tree.insert(left,key,val)
elif key > self.root.key:
right = BSearch_tree()
right.root=self.root.right
self.root.right=BSearch_tree.insert(right,key,val)
return self
答案 0 :(得分:1)
我希望我做对了;)
我建议不要为Tree_Node
而烦恼,而只是跟BSearch_Tree
一样:
import pprint
class BSearch_tree():
def __init__(self, key=None, val=None, root=None):
self.root = root
self.key = key
self.val = val
self.left = None
self.right = None
def insert(self, key, val):
if self.key is None:
self.root = self
self.key = key
self.val = val
elif key == self.key:
self.val=val
elif key < self.key:
if self.left == None:
self.left=BSearch_tree(key,val,self.root)
self.left.insert(key,val)
elif key > self.key:
if self.right == None:
self.right=BSearch_tree(key,val,self.root)
self.right.insert(key,val)
# return self
def __repr__(self):
return '<BSearch_tree: key: "%s", val: "%s", left: "%s", right: "%s" >' % self.key, self.val, self.left, self.right)
# lazy retreaval with recursion
def __getitem__(self, key):
if self.key is None:
raise KeyError
elif key == self.key:
return self.val
elif key < self.key:
if self.left == None:
raise KeyError
return self.left[key]
elif key > self.key:
if self.right == None:
raise KeyError
return self.right[key]
bt = BSearch_tree()
bt.insert(1,'1')
print bt[1]
bt.insert(2,'2')
print bt[2]
try:
print bt[3]
except KeyError:
print '3 not there as expected'
bt.insert(5,'5')
print bt[5]
bt.insert(3,'3')
print bt[3]
pprint.pprint(bt)
我有一种偷偷摸摸的感觉,我应该在某个地方使用self.root
,但我现在还不完全确定。