I found the error and fixed it, I should have put “nodes_to_visit += current_node.children” on line 23 instead of “nodes_to_visit.append(current_node.children)”. But a new question arises. When I produced an error message, it read “‘list’ object has no attribute ‘value’”. I spent quite a long time to figure out the problem because the error message didn’t seem to directly address to the problem. Can anyone tell me why such error message is produced when I put “nodes_to_visit.append(current_node.children)”? so that next time I face similar problem I may address the problem directly.
# Define your "TreeNode" Python class below class TreeNode: def __init__(self, value): self.value = value self.children =  def add_child(self, child_node): print("Adding " + child_node.value) self.children.append(child_node) def remove_child(self, child_node): print("Removing " + child_node.value + " from " + self.value) self.children = [child for child in self.children if child is not child_node] def traverse(self): nodes_to_visit = [self] while len(nodes_to_visit) > 0: current_node = nodes_to_visit.pop() print(current_node.value) nodes_to_visit.append(current_node.children) root = TreeNode("CEO") first_child = TreeNode("Vice-President") second_child = TreeNode("Head of Marketing") third_child = TreeNode("Marketing Assistant") root.add_child(first_child) root.add_child(second_child) second_child.add_child(third_child) root.traverse()
You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility
When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!
If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer!