raylopez99 said:
And many cannot I suppose?
Well, any algorithm that requires storing previous state all the way
back to the original root case is going to have to use some kind of
stack-like data structure.
The fact is, even here there are ways to change the problem so that a
stack isn't required. For example, you can do an in-order traversal of
a tree without a stack as long as the child nodes refer back to the
parent. One implementation I've seen just keeps a "next in-order node"
reference, so all the children except the last point to their sibling,
with that last sibling pointing back to the parent.
But in that situation, you've taken a tree data structure and overlaid a
plain list onto it. I would argue that you haven't so much implemented
a recursive algorithm without a stack, so much as simply changed the
data structure so that it's no longer a recursive algorithm to enumerate
the data structure.
I was thinking--and so far with my N-ary tree it seems to be working--
of storing the 'state variables' of the algorithm (in my case the
nodes that are next to go through the iterative loop)--on the stack.
So you're not really wasting memory, since these nodes are tiny, nor
are you replicating the itteration, insofar as I can tell.
On which stack? The actual call stack? Or an explicit data structure
of your own making? Either way, the algorithm is still recursive. The
difference is that if you create an explicit data structure, now you
have to write all the code to maintain it as well. If you just use the
call stack, your code is not cluttered with details not directly
relating to the algorithm itself.
And I
can't figure out any other way of traversing and/or building the N-ary
tree, without adding pointers within the nodes, which, come to think
of it, is not a bad idea (though storing pointers within the nodes
also is a cost, in terms of extra memory used by each node), but not
the way I'm proceeding at the moment.
That solution is basically the same as what I mention above. But then
you are simply adding a new data structure -- a list -- to your existing
one.
It's not a bad solution, but really...there's nothing wrong with
recursion per se. In a situation where recursion is the clearest,
simplest code to write, you ought to just go ahead and use it. And
there's no reason to implement your own stack; C# has a perfectly good
automatically-maintained stack of its own that you can take advantage of.
That's not to say that there's no need for an alternative stack
structure. Any time that the maintenance of the stack does not itself
correspond exactly to the flow of the code, you need to keep one that is
separate from the regular call stack. But for something like this,
that's not the case.
Pete