Most efficient way of creating tree from adjacency list

后端 未结 2 1702
说谎
说谎 2020-12-28 23:49

I have an adjacency list of objects (rows loaded from SQL database with the key and it\'s parent key) that I need to use to build an unordered tree. It\'s guaranteed to not

相关标签:
2条回答
  • 2020-12-29 00:14

    SortedList is not a good container to use in this context. It is O(n) for insertion operations (the repeated calls to Add()), as it is internally represented as a flat list. Using Dictionary instead of SortedList will be a large improvement, as it is O(1) amortized insertion time.

    0 讨论(0)
  • 2020-12-29 00:17
    1. Put the nodes into a sorted list or dictionary.

    2. Scan that list, pick up each node, find its parent node in the same list (binary search or dictionary lookup), add it to the Children collection of the parent node.

    There's no need for a Stack to put this into a tree.

    0 讨论(0)
提交回复
热议问题