Link to home
Start Free TrialLog in
Avatar of tiger0516
tiger0516

asked on

Traverse a binary tree iteratively

Hi folks,

How can I traverse a binary tree iteratively instead of recursively? (pre-order, in-order, and post order)

The binary tree is just a regular binar tree (not a binary search tree). Each tree is a node, with three elements, node value, pointer to left child, and pointer to right child.

Thanks
Avatar of PaulCaswell
PaulCaswell
Flag of United Kingdom of Great Britain and Northern Ireland image

Hi tiger0516,

This is always an interesting homework question. The joy of it is, however you try to do it, you almost always end up trying to emulate a stack. It's intended to show you that 'sometimes' the recursive solution is the most optimal.

However, it is not always the best! For example, if you want to postpone the search while it os running and go off and do something else for a while, a recursive solution is not easy to manage.

The answer is to hold a stach of levels, ideally growable but I doubt that would impress anyone. Allow yourself, say 100 levels. The stack needs only to contain node pointers.

Whenever you step deeper into the tree, 'push' a pointer to the node you are leaving onto the stack. To step out of the tree by one node, just pop the top pointer off the stack.

Post some code and we'll help you get it right. :-)

Paul
ASKER CERTIFIED SOLUTION
Avatar of hoomanv
hoomanv
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial