Hi all,
I'm looking for a fast algorithm to do the following:
A DataTable has the following columns: ID, ParentID, Title, Body, etc. It
represents webforum conversation threads. ParentID points to the ID of the
parent post.
I'm trying to convert this into a tree structure in memory (e.g. XML).
I understand this can be done with recursion but my algorithm seems to be
too slow, i.e. there are too many loops. Does anyone have an example of a
better algorithm?
Thanks.
Mine is (pseudocode):
For each row in table
{
if parent == 0 // top element
{
row.visited = true;
AttachToTree()
RecursivelySearchForChildRen(row)
}
}
method RecursivelySearchForChildRen(parent)
{
Foreach row in table // TODO need to eliminate this extra loop, too
much iterating
{
if row.visited == false && row.parent == parent
{
row.visited = true;
AttachToParent()
RecursivelySearchForChildRen(row) // call itself again
}
}
}
-Oleg.