public List <string> Run(List <CourseEntry> input) { var orphans = new Dictionary <int, List <CourseNode> >(); var seenNodes = new Dictionary <int, CourseNode>(); var roots = new Dictionary <int, CourseNode>(); var toReturn = new List <string>(); foreach (var course in input) { var parent = course.ParentID; var courseNode = new CourseNode(course.ID, course.Name); seenNodes.Add(courseNode.ID, courseNode); // if the node is a root if (parent == -1) { roots.Add(courseNode.ID, courseNode); } // the node is not a root, find its parent // first, check if we have seen its parent if (seenNodes.ContainsKey(parent)) { // add the node to this parent seenNodes[parent].Children.Add(courseNode); } else { // it is an orphan, add it to the orphan list if (!orphans.ContainsKey(parent)) { orphans.Add(parent, new List <CourseNode>()); } orphans[parent].Add(courseNode); } // now this node need to collect the orphans if (orphans.ContainsKey(courseNode.ID)) { var children = orphans[courseNode.ID]; foreach (var child in children) { courseNode.Children.Add(child); } orphans.Remove(courseNode.ID); } } foreach (var root in roots.Values) { PrintChildren(root, "", toReturn); } return(toReturn); }
public void PrintChildren(CourseNode node, string prefix, List <string> toReturn) { toReturn.Add($"{prefix}{node.Name}"); if (node.Children.Count > 0) { foreach (var child in node.Children) { PrintChildren(child, prefix + "-", toReturn); } } }