我有一个存储过程,它返回一个按树形结构组织的平面名称列表。为了确定每个名称的父级关系,需要使用Depth值。例如,当返回5条记录时(共3层),结果如下:
Depth|Name
----------
0|Ford
1|Compact Cars
2|Pinto
1|Trucks
2|H-Series
我正在尝试通过读取深度值来构造一棵树。有没有显而易见的算法可以将这个数组序列构造成一棵树?我添加了C#标签,因为我可以接受使用LINQ解决此问题,但一般的计算机科学答案也将非常有帮助。
以下是我的当前尝试:
class Record
{
public string Name{ get; set; }
public List<Record> children { get; set; }
}
var previousLevel = 0;
var records = new List<Record>();
foreach (var thing in TreeFactory.fetch(dao))
{
if(this.Depth == 0) {
//Root node
} else if(thing.Depth > previousLevel) {
//A Child of the last added node
} else if(thing.Depth < previousLevel) {
//A Cousin of the last added node
} else {
//A Sibling of the of the last added node
}
previousLevel = this.Depth;
}
所谓“高效”,指的是列表大小达到200,000个元素和树深度达到100级,因此我只是希望找到一些更容易理解的东西。