I have to build add the branches (nodes) to a tree view. I’m struggling to determine what the lowest O(n) technique is.
My data presents as follows:
Id ParentId Value
0 null Bob
1 0 Amy
2 1 Susan
3 1 Matt
4 2 Keith
5 4 Craig
6 4 Derrick
So the tree would look like:

All I can come up with is an n^2 algorithm which for every entry scans every other entry to see if they belong as a sub node.
I also am removing entries from the array to scan as they are being added. So it’s a little less than n^2 if memory serves (probably not).
Are there any better techniques?
Assuming your language has some sort of list/vector/resizable array type, this is pretty easy.
Make an empty list for each ID. Iterate over each row, and if ParentId is not null, add the Id to the ParentId’s list.
You now have the children for each entry in O(n) time.