Algorithm 从记录中构建树结构

Algorithm 从记录中构建树结构,algorithm,sorting,data-structures,tree,binary-tree,Algorithm,Sorting,Data Structures,Tree,Binary Tree,我在数据库中查询以下结构中的记录 ID |术语|父ID 在C#代码中,我有以下类 public class Tree { public string Id { get; set; } public string Term { get; set; } public string ParentId { get; set; } public int Level { get; set; } public IList<Tree> ChildItems {

我在数据库中查询以下结构中的记录

ID |术语|父ID

在C#代码中,我有以下类

public class Tree
{
    public string Id { get; set; }
    public string Term { get; set; }
    public string ParentId { get; set; }
    public int Level { get; set; }
    public IList<Tree> ChildItems { get; set; }
}
尝试使用ID(
string
,尽管我很好奇为什么这不是
int
)到节点(
Tree
对象)的映射(C#)来存储树节点

这将允许您获得与预期O(1)复杂度的ID对应的节点,而不是当前的O(n)复杂度

除此之外,我建议你重新考虑一下你的方法——试着编写只涉及一次输入数据的代码,只使用一个字典——如果父项还不存在,你可以为父项创建一个填充项,只有当你到达该项时才填充其成员。

我会使用字典(哈希表)使其更快。以下是我的伪代码算法:

- create a dictionary mapping ID to IList<Tree> // mapping a node to its children
- create Queue<string,string> of IDs //item (3,5) in the queue corresponds to a node with ID=3 that has a parent with ID=5
- initialize the queue with all the codes with no parent
    - List<Tree> withoutParent = dictionary[null]
    - for each item in withoutParent:
        - add (item.Id, null) to the queue
- while queue is not empty:
    - (id,pid) = delete an item from the queue
    - make a new node t
        - t.Id = id
        - t.parentId = pid
    - t.ChildItems = dictionary[id]
    - for each child in t.ChildItems:
        - add (child.Id, id) to the queue
-创建到IList的字典映射ID//将节点映射到其子节点
-创建ID的队列//队列中的项(3,5)对应于ID=3的节点,该节点具有ID=5的父节点
-使用没有父级的所有代码初始化队列
-列表withoutParent=dictionary[null]
-对于withoutParent中的每个项目:
-将(item.Id,null)添加到队列
-当队列不为空时:
-(id,pid)=从队列中删除项目
-创建一个新的节点t
-t.Id=Id
-t.parentId=pid
-t.ChildItems=字典[id]
-对于t.ChildItems中的每个子项:
-将(child.Id,Id)添加到队列
  • 列ID是否为唯一标识符。如果是,则可以尝试以下操作。不要使用列表,而是使用集合或哈希映射。这是因为如果父项有太多子项,则在列表中查找会减慢操作。如果使用集合,则可以快速查找,也可以快速添加元素

  • 另外,您可以检查order by子句需要多长时间。这可能会真正帮助您加快处理速度。如果ID是聚集索引,您将获得快速排序方式(因为数据已经排序),否则您的查询仍将使用相同的索引

  • 当父级不存在时,您正在创建父级的父级。我会尽量避免这种情况。您可以做的是,如果树中不存在子级的父级,请将其添加到单独的列表中。在查看原始列表后,再进行第二次查找孤立元素。优点是不需要调整大小每次创建父对象的父对象,然后发现父对象恰好位于列表的末尾时,都会出现r树

  • - create a dictionary mapping ID to IList<Tree> // mapping a node to its children
    - create Queue<string,string> of IDs //item (3,5) in the queue corresponds to a node with ID=3 that has a parent with ID=5
    - initialize the queue with all the codes with no parent
        - List<Tree> withoutParent = dictionary[null]
        - for each item in withoutParent:
            - add (item.Id, null) to the queue
    - while queue is not empty:
        - (id,pid) = delete an item from the queue
        - make a new node t
            - t.Id = id
            - t.parentId = pid
        - t.ChildItems = dictionary[id]
        - for each child in t.ChildItems:
            - add (child.Id, id) to the queue