Created
July 21, 2012 00:40
-
-
Save xpando/3154041 to your computer and use it in GitHub Desktop.
Extensions methods for traversing trees using recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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