Skip to content

Instantly share code, notes, and snippets.

@xpando
Created July 21, 2012 00:40
Show Gist options
  • Select an option

  • Save xpando/3154041 to your computer and use it in GitHub Desktop.

Select an option

Save xpando/3154041 to your computer and use it in GitHub Desktop.
Extensions methods for traversing trees using recursion
public static class RecursiveTreeExt
{
public static IEnumerable<T> AsDepthFirstEnumerable<T>(this T head, Func<T, IEnumerable<T>> children)
{
yield return head;
foreach (var node in children(head))
{
foreach (var child in AsDepthFirstEnumerable(node, children))
{
yield return child;
}
}
}
public static IEnumerable<T> AsBreadthFirstEnumerable<T>(this T head, Func<T, IEnumerable<T>> children)
{
yield return head;
var last = head;
foreach (var node in AsBreadthFirstEnumerable(head, children))
{
foreach (var child in children(node))
{
yield return child;
last = child;
}
if (last.Equals(node))
yield break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment