I added an generator function to be able to iterate through a predefined BinaryTree class, but when I run it with the testing code I get a TypeError saying that the BinaryTree class isn't iterable and I'm not sure why. Here is the provided code along with the generator function to traverse the tree as well as the testing code:
# Implement generator function to make class iterable
class BinaryTree:
def __init__(self, content, leftSubtree=None, rightSubtree=None):
self.content = content
self.leftSubtree = leftSubtree
self.rightSubtree = rightSubtree
def __repr__(self):
return str(self.content)
def traverse(self): # Generator implementation
if self.rightSubtree:
for leaf in self.rightSubtree:
yield leaf
yield self.content
if self.leftSubtree:
for leaf in self.leftSubtree:
yield leaf
# Testing code
Node = BinaryTree
if __name__ == '__main__':
s = Node(1) # Binary tree with 1 Node
t = Node(10, s, None) # Binary tree with 10 as content, 1 as left subtree
tree = BinaryTree(20, None, t) # Binary tree with 20 as content, no left subtree and t as right subtree
for x in (s, t, tree):
print(x)
for node in tree:
print(node)
Here is the error that gets printed out afterwards:
1
Traceback (most recent call last):
10
20
File "...binaryTree_adt.py", line 34, in <module>
for node in tree:
TypeError: 'BinaryTree' object is not iterable
Process finished with exit code 1
I know that for generators you don't need to create an iterator class as the generator will iterate through the items in a similar fashion. When I change the name of the "traverse" method to iter I don't get any errors, but when the name is changed I do.