Skip to content

Instantly share code, notes, and snippets.

@irskep
Created February 20, 2016 21:22
Show Gist options
  • Save irskep/59db188b1e8c32b9e586 to your computer and use it in GitHub Desktop.
Save irskep/59db188b1e8c32b9e586 to your computer and use it in GitHub Desktop.
def postorder_traversal(self, node=None):
"""Yields every node in the tree in post-order"""
root = node or self.root
stack = deque([(root, 'yield'), (root, 'children')])
while len(stack) > 0:
(node, action) = stack.pop()
if action == 'yield':
yield node
elif action == 'children':
for i in reversed(range(len(node.children))):
stack.append((node.children[i], 'yield'))
stack.append((node.children[i], 'children'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment