[英]Type error when trying to build binary search tree in python
I am trying to build a BST but when I try to run the program I get the following error:我正在尝试构建 BST,但是当我尝试运行程序时出现以下错误:
TypeError: 'method' object is not iterable
I am not sure why this is happening since I would assume the in_order_traversal method would be an attribute of the BST class.我不确定为什么会发生这种情况,因为我假设 in_order_traversal 方法将是 BST class 的一个属性。 Below is my code.下面是我的代码。
class BST:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
#
def add_child(self,data):
if data == self.data: #check if value already exists in tree
return
if data <self.data: #should go on the left side then
if self.left: #check if left tree has a value
self.left.add_child(data) #if it has a value, use add_child method to add another child to the left
else: #if it does not have a value
self.left = BST(data)
else:
if self.right:
self.right.add_child()
else:
self.right = BST(data) #if there is no right tree, init a new right tree with data
#visit left, root then right
def in_order_traversal(self):
elements = []
if self.left:
elements += self.left.in_order_traversal()
elements.append(self.data) #append the root
if self.right:
elements += self.right.in_order_traversal
return elements
def build_tree(data):
root = BST(data[0])
for i in range(1,len(data)):
root.add_child(data[i])
return root
if __name__ == '__main__':
numbers = [12,3,1,20]
numbers_tree = build_tree(numbers)
print(numbers_tree.in_order_traversal())
def in_order_traversal(self):
elements = []
if self.left:
elements += self.left.in_order_traversal()
elements.append(self.data)
if self.right:
elements += self.right.in_order_traversal() #CHANGE
return elements
You actually forgot to write parenthesis after in_order_traversal
method, which caused the error.您实际上忘记在in_order_traversal
方法之后写括号,这导致了错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.