属性错误: 类型对象'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:类型对象'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)
  1. 您正在调用没有参数的printTree():
self.left.printTree()
...
self.right.printTree()

然而,您定义它接受val,这只是未使用的方式:

def printTree(self,val):

替换为:

def printTree(self):
  1. 方法printTree()是一个实例方法,不是@classmethod也不是@staticmethod。这意味着它需要调用BSTNode的活动实例/对象,该实例/对象将作为self参数传递。所以这个调用是不正确的:
BSTNode.printTree(BSTNode)

必须是:

root.printTree(BSTNode)

那么考虑到我上面的第一点,最后应该是:

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)

这将产生相同的输出。

最新更新