mark_c wrote:I think it's due to how the binary tree is visited, how do I fix it?

You are iterating a given Node's parents in backward order from leaf up to root. You are appending each parent's text to the *end* of the path string, which is what you should do when iterating forward. But when iterating backward, you need to prepend the text to the *front* of the string instead.

in the last version of the code, there are two nested cycles (while) and mean that we are in the presence of an algorithm with a O (n ^ 2) complexity.

In the first version, however, a main function that contains a loop (while), call another function wich contain another loop (while), I think that also this version is an O (n ^ 2) complexity.

If I use as input a number of directories that build 1 million paths, I get it as the final run time: 17 minutes for the first version, and 30 minutes for the second, is it due to compiler optimizations?

mark_c wrote:If I use as input a number of directories that build 1 million paths, I get it as the final run time: 17 minutes for the first version, and 30 minutes for the second, is it due to compiler optimizations?

No, it is simply because your looping code is very inefficient in general.

First off, make sure to call ListBox1->Items->BeginUpdate() to disable screen updated on every call to Add(), and then call ListBox1->Items->EndUpdate() when done. Or, add the strings to a separate TStringList first, then assign that to the TListBox when done.

But more importantly, you are using a GetFirst/GetNext loop to iterate through every node in the tree from top to bottom without regard to any branching, so you end up generating related paths multiple times instead of caching and reusing them. For example, lets look at your first 3 nodes:

Couple that with your use of TTreeNode::GetNext() to touch ALL nodes in the Tree, you are not gaining any performance benefits, not to mention you are back to accessing the same nodes multiple times (since AddNodeToList() already touches child nodes, and then you touch them again in your own loop).

Since your Button event is only adding Level 0 nodes to the ListBox, there is no reason to use TTreeNode::GetNext() to touch any nodes at levels 1 and higher. Use TTreeNode::GetNextSibling() instead to enumerate only the nodes at Level 0, like I showed earlier: