quote:
Original post by omegasyphon
just curious why do you even want to search a binary tree with a non recursive function? sure it can be done but whats the point? its not more efficient.
Actually, searching a binary search tree is a lot more efficient without recursion.
The reason recursion is used a great deal with tree''s is because it is a simple and elegant solution.
recursive BST search:
|
what a really simple routine, right? Its pretty too.
The problem is that recursion in this example is a waste. The entire purpose of recursion is to store the state of an earlier operation for use later. In a BST search, we do not need to know which path the routine traveled down. This method saves a stack frame for every level of the tree, and then must pop it all from the stack once it reaches a termination point.
Since the BST search algorithm has no use for remembering data from previous levels, and just needs to exit out when it reaches a termination point, an iterative solution to this problem is much faster:
|
This version is not much larger, and if you run it, it will be much faster, since it does not require a stack frame creation for each level of the tree.
The same goes with Binary Search Tree insertions, since you do not need to remember the path on the way down, there is no need for recursion.
===============================================
Have I no control, is my soul not mine?
Am I not just man, destiny defined?
Never to be ruled, nor held to heel!