FAQ: Trees: Python - Tree Implementation V: Traversing Root to Leaf

This community-built FAQ covers the “Tree Implementation V: Traversing Root to Leaf” exercise from the lesson “Trees: Python”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

Complex Data Structures

FAQs on the exercise Tree Implementation V: Traversing Root to Leaf

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

I don’t get these complicated instructions; I mean, I get them, but what’s wrong with:

def traverse(self):
for child in self.children:

Should a method not call itself on another instance of the same class object? I tested the code in IDLE and it seemed to work just fine.


should be:
print(child.value) instead of child.traverse()

the function doesn’t come out if you don’t write the logic of it.
The basic function of traverse is
for element in whole:

instead of calling itself.

1 Like

I don’t think you understood his question.

The logic of his solution is simpler to do a traversal of a tree then the provided solution.

In fact, depending on the exact structure of his provided traversal, it is easy to make an in-order, pre-order, or post-order traversal.

Meanwhile, the provided solution is more complicated by using lists to keep track of things when we don’t need to.


Yes, that is what I meant.

I guess they teach it the more complicated way because it’s prior to the lesson on recursion in Python, when following the computer science path.

Welcome to the community.


By the way what does this ‘nodes_to_visit = [self]’ do? I am unable to understand its use in the code.


List nodes_to_visit is used as a store of nodes that have to be processed inside the while loop. So when we run the traverse method on the root element (root.traverse()) this line simply initializes this list with this root element (self for root is root :slight_smile:).

Then the while loop continually pops (removes) the first element from this list and adds children of the removed element as next elements to the list.


Before doing the steps of the exercise I tried to write the logic for the .traverse() method and I came up with this:

      for child in self.children:
        if len(child.children) > 0:
          for grandson in child.children:

It does print every parent and child but in a different order than the solution provided by Codecademy. Actually, the solution provided by Codecademy prints second_child before first_child, and I still don’t know why and if this is done on purpose for some reason. I dont see any logic to it right now (it probably just does not matter since they are at the same level…).

My code prints:

Head of Marketing
Marketing Assistant

while Codecademy’s:

Head of Marketing
Marketing Assistant

Is the traverse() method I wrote correct?

I don’t understand why the instructor is always making simple things more complicated than it needs to be.


I believe that .pop() pulls from the end of the list, rather than the beginning. So when you add current_node.children, they are added in order, but you are “popping” them in reverse order.

In this instance it doesn’t make much of a difference, but it would be a problem if the nodes were ordered in some way.

Its a weird and sloppy execution of the solution.

clearly the best solution.

Using .pop() it is simple to make them appear in list order by using .pop(0) instead. If for some reason child order was important, this would solve any issue when using the .pop() method for this problem. I found that in the quiz after this the instructor made a point of going over how the order was effected by the .pop(), which I felt cleaned up this sloppiness in the lesson. Also, at this point, we should expect the nuances of .pop() and know that it will work this way when implemented as such?

Anyway, as I commented, the recursive method sholomkeller suggests is obviously superior anyhow, given it’s simplicity.

Hello everybody!

I understood the logic of the exercise, but I do not get this part:

def traverse(self):
nodes_to_visit = [self]
while len(nodes_to_visit) > 0:
current_node = nodes_to_visit.pop()
nodes_to_visit += current_node.children

When they use in the last line current_node.children… What is the part .children doing?

hello lovely people.
how come this doesnt work? thank you.

def traverse(self):
nodes_to_visit = [self]
while len(nodes_to_visit) != 0:
current_node = nodes_to_visit.pop()
nodes_to_visit += current_node.children

Hey guys,

Can someone explain why I get the error “AttributeError: ‘list’ object has no attribute ‘value’” when using the code with the “append” function instead of the “plus sign” ? Apparently, it has smth to do that append does not create a copy of a list i.e. more efficient run time. However, I cannot wrap my head around where the initial code breaks down using the append method. Thanks a lot!

Code with append function and original solution hided via comment:

# 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:  #Ich brauche das len, damit computer versteht, es gibt da was zu suchen!
     current_node = nodes_to_visit.pop() #important: pop by default pops the last element of a list!!
     if len(current_node.children) >0:

#def traverse(self):
    #nodes_to_visit = [self]
    #while len(nodes_to_visit) > 0:
      #current_node = nodes_to_visit.pop()
      #nodes_to_visit += current_node.children

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



My question is about the traverse function inside the TreeNode class

It is because you try to append a list (self.children) to the “nodes_to_visit” list.
So when you try then to print the value, you get this error, because you method doesn’t works on a list. Instead, merging list will keep the instances in the list and the value field will be accessible.

1 Like