【发布时间】:2022-01-16 17:23:07
【问题描述】:
我正在尝试形成二叉搜索树并打印它。我收到以下错误:
self.root.left.printtree() AttributeError: 'Node' object has no attribute 'printtree'
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
class Binarysearchtree():
def __init__(self,data):
self.root=Node(data)
def insert(self,data):
if self.root.data>data:
if self.root.left==None:
self.root.left=Node(data)
else:
self.root.left.insert(data)
elif self.root.data<data:
if self.root.right==None:
self.root.right=Node(data)
else:
self.root.right.insert(data)
else:
self.root.data=data
def printtree(self):
if self.root.left:
self.root.left.printtree()
print(self.root.data)
if self.root.right:
self.root.right.printtree()
a=Binarysearchtree(23)
a.insert(20)
a.insert(24)
a.printtree()
【问题讨论】:
-
缩进在 Python 中很重要。上面的代码有不同级别的缩进,这使得你很难理解你想要做什么。您应该编辑问题并确保缩进确实与您正在执行的操作相匹配。
-
您已经在树上而不是在节点上定义了
printtree方法......并且您正在节点上调用它。要么在节点上定义它,要么让它接受一个节点作为参数。
标签: python class binary-tree binary-search-tree