# Given the following code, in what order will we visit the nodes?

hello there, can someone please explain how the tree is traversed in this quiz, how the value travels through the traverse function:

``````class TreeNode:
def __init__(self, value):
self.value = value
self.children = []

self.children.append(child_node)

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("A")
first_child = TreeNode("B")
second_child = TreeNode("C")

root.traverse()
``````

does âAâ âBâ âCâ go into the ânode_to_visitâ list when it is called by âroot.traverseâ ??

if so, while âcurrent_nodeâ starts to .pop() the values, why do we have this line ânodes_to_visit += current_node.childrenâ.
doesnt this line make the loop infinite because we are popping and adding again?

The key concept to understand here on how traversing a tree works, is that you start with the root node (thatâs why the first nodes_to_visit is self), and then you go from the root to its children, and from the children to their children, and so onâŚ until you have no more nodes left.

This is why when youâre done traversing a node, you pop() it, and then add its children so that you can continue traversing down the line.

Pop()-ing a node removes it from the list, so you donât go over the same node twice, so the loop is not infinite. And when you add its children, you donât add the parent node as well, so youâre never adding the same node twice either.

1 Like

OH OK GOT IT we are always adding the child of the current node!!!

one last question if you have time, how come the order of traversing starts A => C => B ?
i didnt quite get that part either.

thanks a lot

No problem!

Try to visualize the tree nodes and their relationships, and the order in which they are added and removed to the traversal, and youâll figure it out yourself.

The root node here is âAâ, itâs child is âBâ, and "B"s child is âCâ.

You start traversing with the root âAâ, so this is how the list looks `["A"]`, then you `pop()` it, now you have an empty list `[]`, then you add "A"s children (note that here youâre adding its direct children only). Then you `pop()` "A"s only childâŚ You see where this is going?

EDIT:
Ah sorry, I just noticed that youâre asking why itâs going âAâ, âCâ, then âBâ, and that âBâ and âCâ are both direct children of âAâ.

Well, to understand this then, you have to look at the order the children were added, and remember that pop() removes the last element from a list by default.

1 Like

oh ok thanks for the message, so basically because it removes the last element, i guess thats why we will visit the elements A => C => B