python - AttributeError:类型对象'BSTNode'没有属性'left'
问题描述
我试图在 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 object 'BSTNode' has no attribute '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()
没有参数的情况下调用:
self.left.printTree()
...
self.right.printTree()
但是,您将其定义为 accept val
,顺便说一句,它只是未使用:
def printTree(self,val):
将其替换为:
def printTree(self):
- 该方法
printTree()
是一个实例方法,而不是一个@classmethod
nor@staticmethod
。这意味着它需要BSTNode
调用一个活动实例/对象,该实例/对象将作为self
参数传递。所以这个调用是不正确的:
BSTNode.printTree(BSTNode)
一定是:
root.printTree(BSTNode)
然后考虑我上面的第1点,最后应该是:
root.printTree()
root
您当前的活动类型实例在哪里BSTNode
。
经过这些修复,它会成功
5
6
12
15
18
21
替代解决方案
如果您不想printTree()
成为实例方法,请@staticmethod
改为使用它。
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)
这将产生相同的输出。
推荐阅读
- oauth - 通过 G Suite Admin SDK 对第三方应用的 API 访问
- c# - 如何避免循环引用 asp.net core mvc [HttpPost("add-recipe")] web api
- vue.js - 使用scss文件时Vue“找不到这些相关模块”
- html - 在 flexdashboard 中添加指向 PNG 的超链接
- python - Keras 子类化类型错误:tf__call() 为参数“训练”获得了多个值
- ansible - 在 Ansible 中处理跳过的主机
- node.js - waitForSelector 突然不再在 puppeteer 中工作
- python - 如何使用python获取当前时间
- javascript - 无法让状态在本机反应中工作
- python - 如何在 chemspipy(化学蜘蛛)中返回实验或估计的化学性质?