Iterative Tree Traversals in Python

Last updated on
21st
of April,
2016.

Tree traversals are most naturally expressed in recursion, but iterative versions are cool too, plus they take only O(1) space.

Inorder traversal: Visit the left subtree first, then the node, and the right subtree.Preorder traversal: Visit the node first, then the left subtree, then the right subtree.Postorder traversal: Visit the left subtree, then the right subtree, then the node.

The concept behind the iterative versions are as follows.

There are three states a traversal can be in:

You’ve just visited the left or right child of a parent node.

You’ve just gone back to a parent node from its left child.

You’ve just gone back to a parent node from its right child.

Keeping three pointers: prev to designate the previous node, curr to designate the current node, and _next to designate the next node, we can codify the above conditions like so: