Created
November 4, 2011 17:29
-
-
Save jrwren/1339932 to your computer and use it in GitHub Desktop.
ienumerable tree traversal
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
| /// <summary> | |
| /// breadth first traversal | |
| /// </summary> | |
| /// <typeparam name="T"></typeparam> | |
| /// <param name="root"></param> | |
| /// <param name="childrenSelector"></param> | |
| /// <returns></returns> | |
| public static IEnumerable<T> Traverse<T>(this T root, Func<T,IEnumerable<T>> childrenSelector) | |
| { | |
| yield return root; | |
| IEnumerable<T> childrens = childrenSelector(root); | |
| foreach(var child in childrens) | |
| { | |
| if (child!=null) | |
| yield return child; | |
| } | |
| foreach (var child in childrens) | |
| { | |
| if (child != null) | |
| foreach (var childsKids in childrenSelector(child)) | |
| yield return childsKids; | |
| } | |
| } | |
| /// <summary> | |
| /// depth first traversal | |
| /// </summary> | |
| /// <typeparam name="T"></typeparam> | |
| /// <param name="root"></param> | |
| /// <param name="childrenSelector"></param> | |
| /// <returns></returns> | |
| public static IEnumerable<T> TraverseDeepthFirst<T>(this T root, Func<T, IEnumerable<T>> childrenSelector) | |
| { | |
| yield return root; | |
| IEnumerable<T> childrens; | |
| while ((childrens = childrenSelector(root)) != null) | |
| { | |
| foreach (var child in childrens) | |
| { | |
| if (child != null) | |
| { | |
| yield return child; | |
| foreach (var childsKids in childrenSelector(child)) | |
| yield return childsKids; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment