I've got a binary tree, where the nodes interact with data. I initially implemented a standard post order recursive traversal.
def visit_rec(self, node, data):
if node:
self.visit_rec(node.left, data)
self.visit_rec(node.right, data)
node.do_stuff(data)
I thought I could improve it by using generators so that I can use the same traversal method for other uses, and not have to pass the same data around constantly. This implementation is shown below.
def visit_rec_gen(self, node):
if node:
for n in self.visit_rec_gen(node.left):
yield n
for n in self.visit_rec_gen(node.right):
yield n
yield node
for node in self.visit_rec_gen():
node.do_stuff(data)
However, this was far slower than the previous version (~50s to ~17s) and used far more memory. Have I made a mistake in my generator function version? I'd prefer to use this method but not at the expense of performance.
EDIT: Something I should have mentioned initially was that these results were obtained under PyPy 2.3.1, rather than standard CPython.