"Trees" question


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)
  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()

root = TreeNode("CEO")
first_child = TreeNode("Vice-President")
second_child = TreeNode("Head of Marketing")
third_child = TreeNode("Marketing Assistant")



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! :slight_smile:

That error message appears because at some you’ve attempted to access the .value attribute on an item which is a list object. As a very short example-

[1, 2, 3].value
AttributeError: 'list' object has no attribute 'value'

Find out which section of code is running and look for any statements which use the .value attribute and make sure the datatype you’re using is an instance of your TreeNode class and not a list.

As for the difference between your code note that append adds a single identifier to a list. This could be an integer or a string, it could be an entirely different list or it could even be the list itself. The += operator on the other hand is more directly associated with the .extend method which adds a sequence to your list (e.g. the elements of another list or tuple).

This suggests the data type you’re appending is not what you expect it to be. Maybe try printing it out so you know for certain.

1 Like