diff --git a/ICD.Common.Utils/RecursionUtils.cs b/ICD.Common.Utils/RecursionUtils.cs index f6a427a..a0bca92 100644 --- a/ICD.Common.Utils/RecursionUtils.cs +++ b/ICD.Common.Utils/RecursionUtils.cs @@ -462,5 +462,39 @@ namespace ICD.Common.Utils start = next; } } + + /// + /// Returns all of the nodes in the tree via depth-first search. + /// + /// + /// + /// + /// + [NotNull] + public static IEnumerable DepthFirstSearch([NotNull] T root, [NotNull] Func> getChildren) + { + if (root == null) + throw new ArgumentNullException("root"); + + if (getChildren == null) + throw new ArgumentNullException("getChildren"); + + IcdHashSet visited = new IcdHashSet(); + Stack stack = new Stack(); + + stack.Push(root); + + while (stack.Count != 0) + { + T current = stack.Pop(); + if (!visited.Add(current)) + continue; + + yield return current; + + foreach (T child in getChildren(current).Reverse()) + stack.Push(child); + } + } } }