From 81d1a97304b9911d7c4ddfef0f3e2776ff5134de Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Tue, 1 Dec 2020 16:53:10 -0500 Subject: [PATCH] feat: Added DepthFirstSearch method to RecursionUtils --- ICD.Common.Utils/RecursionUtils.cs | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) 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); + } + } } }