Algorithm 从记录中构建树结构
我在数据库中查询以下结构中的记录 ID |术语|父ID 在C#代码中,我有以下类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 {
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)添加到队列
- 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