Suppose I have a list of nodes which represent a nested set hierachy (examples are in pseudo c#).
class Node
{
public decimal left;
public decimal right;
public decimal id;
public void AddChild(Node child) {...}
...
}
List<Node> nodes = GetFlatNodesWithoutChildrenSetFromDatabase();
The fields left
, right
and id
get filled, since these values are stored in some database.
What is an efficient way to transform this flat list into a hierachy, that means filling in the appropriate children nodes for each parent node?
One way is just to find all ancestors of each node, sort them to find the parent node and add the child node to that node.
foreach (var n in nodes)
{
var parent = nodes.Where(i => i.left < n.left && i.right > n.right).OrderBy(i => i.right - n.right).FirstOrDefault();
if (parent != null)
parent.AddChild(n);
}
But this is rather inefficient.
Is there a better (that means faster) approach?
EDIT
Possible solution (as suggested by Chris):
var stack = new Stack<Node>(nodes.Take(1));
foreach (var n in nodes.Skip(1))
{
while (stack.Peek().right < n.left)
stack.Pop();
stack.Peek().addChild(n);
stack.Push(n);
}
Nodes have to be ordered by left
.