Answers for "C# walk down a tree and back"

C#
0

C# walk down a tree and back

public static IEnumerable<T> Traverse<T>(T item, Func<T, IEnumerable<T>> childSelector)
{
    var stack = new Stack<T>();
    stack.Push(item);
    while (stack.Any())
    {
        var next = stack.Pop();
        yield return next;
        foreach (var child in childSelector(next))
            stack.Push(child);
    }
}
Posted by: Guest on September-03-2020

C# Answers by Framework

Browse Popular Code Answers by Language