Instead of calling self.left/right.
in
_order_list()
, you're calling self.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:
class Tree(object):
...
def in_order(self):
if self.left is not None:
for value in self.left.in_order():
yield value
yield self.value # <-- yielding the value of the node, not the node itself
if self.right is not None:
for value in self.right.in_order():
yield value
...
tree = Tree(...)
in_order_values = list(tree.in_order())
That way, you don't have to create a list if you only want to iterate over the values:
for value in tree.in_order():
...
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 to in_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:
class Tree(object):
...
def in_order(self):
if self.left is not None:
for node in self.left.in_order():
yield node
yield self # <-- yielding the node itself
if self.right is not None:
for node in self.right.in_order():
yield node
You probably want to do this, because not only can you still access the values of the nodes:
for node in tree.in_order():
do_something_with(node.value)
but also you can do whatever you want with the nodes:
for node in tree.in_order():
whatever(node.some_other_attribute)