I have the following structure:
MyClass { guid ID guid ParentID string Name }
I would like to create an array that contains the elements in the order in which they should be displayed in the hierarchy (for example, according to their "left" values), as well as a hash that displays a pointer to the indent level.
For instance:
ID Name ParentID ------------------------ 1 Cats 2 2 Animal NULL 3 Tiger 1 4 Book NULL 5 Airplane NULL
This will create the following objects:
// Array is an array of all the elements sorted by the way you would see them in a fully expanded tree Array[0] = "Airplane" Array[1] = "Animal" Array[2] = "Cats" Array[3] = "Tiger" Array[4] = "Book" // IndentationLevel is a hash of GUIDs to IndentationLevels. IndentationLevel["1"] = 1 IndentationLevel["2"] = 0 IndentationLevel["3"] = 2 IndentationLevel["4"] = 0 IndentationLevel["5"] = 0
For clarity, it looks like this:
Airplane Animal Cats Tiger Book
I would like to iterate over the items the least number of times. I also do not want to create a hierarchical data structure. I would prefer to use arrays, hashes, stacks or queues.
Two goals:
- Keep the identifier hash at the indent level.
- Sort a list that contains all objects according to their left values.
When I get a list of elements, they do not have a special order. Siblings must be ordered by the Name property.
Update: It may seem like I havenβt tried to come up with a solution myself and just want others to do the work for me. However, I tried to come up with three different solutions, and I was stuck on each. One reason may be that I was trying to avoid recursion (possibly by mistake). I do not send partial solutions that I still have, because they are incorrect and can adversely affect the decisions of others.
source share