Answer the question
In order to leave comments, you need to log in
How to quickly topological sort a tree from a list?
Hello!
There is a list with attributes (Name, ID, ParentID), which is a tree of different nesting levels. What is the fastest way to restore a tree from this list? Thanks
Answer the question
In order to leave comments, you need to log in
Well, for example like this:
class TreeNode:
def __init__(self):
self.children = []
self.name = None
def add_child(self, child):
self.children.append(child)
def set_name(self, name):
self.name = name
entries = {}
for entry in data:
parent = entries.get(entry.ParentID, TreeNode())
child = entries.get(entry.ID, TreeNode())
parent.add_child(child)
child.set_name(entry.Name)
entries[entry.ParentID] = parent
entries[entry.ID] = child
root = entries[RootID]
I don't quite understand the problem you are trying to solve.
How to quickly topological sort a tree from a list?You actually have arcs (arcs) of the graph. You can fill in a more convenient data structure from this data (adjacency list, for example) and run the topological sorting algorithm on it. For example, based on depth-first search. That is, using DFS (depth-first search, depth-first search), we look for a node (vertex, node, vertex) from which there are no outgoing arcs (sink node), assign it a value equal to the number of nodes, remove it from the graph, repeat . Number - node position in the resulting list. Complexity O(m+n), where n is the number of nodes, m is the number of arcs. This is if a topologically sorted list of nodes is enough for you.
What is the fastest way to restore a tree from this list?This is another question. What do you have in mind? What is the meaning of 'restore'? You have a tree (as a special case of a graph) already given a list of arcs, in fact, in what form do you need to present it?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question