Consider the following code implementing a depth first search on a Rose Tree:
public class RoseTree<T>
{
public T Value;
public IEnumerable<Lazy<RoseTree<T>> Children;
public IEnumerable<T> Flatten()
{
yield return Value;
foreach (var childValue in Children.SelectMany(t => t.Value.Flatten()))
yield return childValue;
}
}
I was struggling to come up with an equivalent non-recursive equivalent. In particular, though a strict non-recursive, quasi-equivalent function is easy to come by, e.g:
public IEnumerable<T> FlattenIteratively()
{
var roseTreeQueue = new Stack<RoseTree<T>>();
var values = new Queue<T>();
roseTreeQueue.Push(this);
while (roseTreeQueue.Any())
{
var top = roseTreeQueue.Pop();
values.Enqueue(top.Value);
foreach (var child in top.Children.Reverse())
roseTreeQueue.Push(child.Value);
}
return values;
}
While this yields the same result as Flatten
for finite trees with defined values, it fails for infinite trees or for trees with undefined values. Does anyone see a way of writing a non-recursive method for traversing this structure with the same characteristics as the recursive method.
Note: given C#'s rewriting of yield return
functions, calling the first method recursive
is somewhat misleading. If anyone has a more precise term, I'd be happy to have it.