I have a recursive method that I’m using to walk over a red black tree, and store various node information (in the list storage).
def _walk (self, storage, func, starting_node) :
if starting_node is not self._nil :
self._walk(storage, func, starting_node.left)
storage.append(func(starting_node))
self._walk(storage, func, starting_node.right)
However, I’d like to re-implement this method so that it builds a generator (from what I understand this should save both time and memory). What’s the “best” way of doing that?
Begin by decoupling the action from the walking
traverseis roughly equivalent toor this generator expression
You can reduce the amount of stack used by manually optimising the tail recursion