What is the most efficient way to get an ordered list from a Tree (Diagram)?
I'm using a diagram control which contains a Node with links to its parents as well as its children. I want to flatten the tree but in order. What's the fastest and most efficient way to do this; preferably in C#.
Here's an example of a tree. I'm having difficulties coming up with a good description of the order so I apologize. The order should list all nodes in order of their creation. For example, in the tree blow, a valid order would be (Root,A,B,C,G,D,H,E,F). This order guarantees that no Node is added to the list before its parent(s).
Your graph is no tree, since a node can have multiple parents. I assume you have a directed acyclic graph (DAG). Your ordered list is called a toplogical ordering of that directed graph, which exists if and only if the graph is acyclic. Luckily for you such an ordering can be produced with linear running time.
You can do this with a depth-first search starting from the root(s):
public static IEnumerable<Node> GetTopologicalGraphOrdering(IEnumerable<Node> roots)
{
var list=new List<Node>();
var visited=new HashSet<Node>();
Action<Node> visit = null;
visit = (n)=>
{
if(visited.Add(n)
{
foreach(Node child in n.Children)
{
visit(child);
}
list.Add(n)
}
}
foreach(Node n in roots)
{
visit(n);
}
return list.Reverse();
}
(Untested notepad code)
Note that this naive implementation will cause a stack overflow for deep graphs. Switch to an explicit stack or an alternative algorithm, if that becomes a problem.
Read the wikipedia article Topological sorting for more details.
链接地址: http://www.djcxy.com/p/30468.html