我试图用python构建一个二进制搜索树。 这是我的节点类:
class BSTNode:
def __init__(self,val):
self.left = None
self.right = None
self.val = val
这个类包含一个名为printTree
的函数,它应该按顺序打印树。以下是printTree函数:
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()
当我执行函数时,它给出了AttributeError:type对象“BSTNode”没有属性“left”
这是我的全部代码:
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()
,但没有参数:但是,您将其定义为接受
val
,顺便说一句,它是未使用的:替换为:
printTree()
是一个实例方法,而不是@classmethod
或@staticmethod
。这意味着它需要调用BSTNode
的活动实例/对象,该实例/对象将作为self
参数传递。所以这个电话是不正确的:它必须是:
考虑到我上面的第1点,最后应该是:
其中
root
是BSTNode
类型的当前活动实例在这些修复之后,它将是成功的
替代解决方案
如果不希望
printTree()
成为实例方法,请将其改为@staticmethod
这将产生相同的输出
相关问题 更多 >
编程相关推荐