both recursion as well as vector based iterative process can be used for DFS tree(b-tree) traversal. In both the cases, we need extra space either in the stack while recursive calls or in a vector. Does any technique exists which doesn’t need space or needs min space?
Share
If you are searching a binary tree, you can represent each path taken as a pattern of bits. Accordingly, you can keep searching downwards from a root point, and keep track of your progress by twiddling the bits in a binary word. You’ll need one bit for each level.
e.g.
If we start searching at A, the search specified by ABD is 00 (left – left); the next is 01, corresponding to left-right, or ABE; 10 is A-C-No child; and 11 is ACF.
Notice that the least significant bit indicates the direction to turn at the end of the traversal (that is, it selects the leaf); if the bit sequence is read the other way, this method would specify a breadth-first traversal.
You keep revisiting the same nodes, as a consequence of storing less information.
Note that this amounts to a linear scan of your data, thus destroying the benefits of having a tree. If you are too space constrained to be able to afford a stack, I suggest that you use a pre-allocated vector. If you keep that sorted, you can do things like binary searches, which will be rather more efficient than this.