Thursday, October 23, 2008

Non recursive algorithm for Post Order Traversal

For Pre,Post and In order traversals of a Binary tree,
it is very easy to write recursive programs/algorithms.
But when it comes to a non-recursive solution, it becomes
rather difficult. Though pre-order and in-order traversals
have non-recursive algorithms, which are slightly easier
to implement/understand, post-order is a tough nut to
crack.

Not any more.
Here is an easy to understand non-recursive algorithm
for post-order traversal :
Fact I : Post order traversal(Left-Right-Root) is the exact opposite
of Root-Right-Left traversal(RoRiL)(Prove it!).
Fact II : And a non-recursive algo for Pre-order(RoLRi) is equally good
for RoRiL.

So, just use the non-recursive algo for RoRiL(which is similar to Pre-order)
and traverse it backwards.(that's the post order traversal)

(Pre-order Non Recursive Algorithm)

2 comments:

Anonymous said...

thank you so much for this post. i have been looking for the answer for sometime now.

Anonymous said...

thank u for the post

Blog Archive