I’ve created a method of a TreeNode class that I’m wanting to return a flat list of an in order tree traversal
My sample tree is:

The in order traversal output should be: [1, 1, 0, 2, 1, 3, 1, 1, 0]
but I’m getting: [2, 1, 1, 0, 1, 3, 1, 1, 0]
Here is my code:
def in_order_list(self, r = []):
hasLeft = self.left is not None
hasRight = self.right is not None
if self is None:
return
else:
if hasLeft:
self.left.in_order_list(r)
r.append(self.value)
if hasRight:
self.right.in_order_list(r)
return r
Would anyone be able to give me a clue as to why this is happening?
Thanks
Alex
Instead of calling
self.left/right.in_order_list(), you’re callingself.left/right.pre_order_list().To accomplish what you want to do a generator function might be better (less memory-consuming and more pythonic) than to accumulate the values in a list:
That way, you don’t have to create a list if you only want to iterate over the values:
The algorithm works like this: the generator first descends recursively along the left branch of every node until it hits one with no left sub-node. Then it yields the value of the current node. After that it does the same on the right sub-node, but starting at the current node, not the root node. If we assume there are no cycles in the tree and no infinite branches, then there will definitely be leaf nodes, i.e. nodes with no left or right sub-node. IOW nodes, for which both base cases (
self.left/right is None) are reached. Therefore the recursive calls will return, hopefully before we’re out of memory or hit the stack limit.The loop over
self.left/right.in_order()is necessary due to the fact that what the call toin_order()returns is a generator, hence the name generator function. The returned generator must be exhausted somehow, e.g. through a loop. In the body of the loop we re-yield the values up one level, where they’re re-yielded again, until they reach top level. There we use the values.If you want to retrieve the nodes themself instead of only their value fields, you could do it like this:
You probably want to do this, because not only can you still access the values of the nodes:
but also you can do whatever you want with the nodes: