我有這樣的樹結構,其中,節點可以具有多個節點構造的樹。我怎樣才能使用這種數據結構
public class Node
{
public Node()
{
ChildLocations = new HashSet<Node>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual int? ParentLocationId { get; set; }
public virtual ICollection<Node> ChildLocations { get; set; }
}
現在,我想在此結構中添加一個parent-child
值的列表。像:
{1,A} -> {2,B}
{1,A} -> {3,C}
{1,A} -> {4,D}
{3,C} -> {5,E}
{3,C} -> {6,F}
構建樹是這個樣子:
1A
/| \
2B 3C 4D
/\
5E 6F
最後,它返回root
參考。
我已經出來了這個解決方案。但我對遞歸部分沒有信心。這是正確的?
public class Tree
{
Node root;
public Node Root
{
get { return root; }
}
public void Add(int parentId, string parentName, int childId, string childName)
{
if (root == null)
{
root = new Node { Id = parentId, Name = parentName };
root.ChildLocations.Add(new Node { Id = childId, Name = childName });
}
else
{
Add(root, parentId, parentName, childId, childName);
}
}
private void Add(Node node, int parentId, string parentName, int childId, string childName)
{
if (node == null)
{
return;
}
if (node.Id == parentId)
{
node.ChildLocations.Add(new Node { Id = childId, Name = childName });
return;
}
foreach (var n in node.ChildLocations)
{
Add(n, parentId, parentName, childId, childName);
}
}
}
我會說它..「你有什麼嘗試?」 – 2012-08-06 04:21:08
你似乎有這個課程?你需要什麼具體的幫助?使用遞歸實現一個添加函數來查找父節點應該很容易。 – nunespascal 2012-08-06 04:29:36
我認爲你需要指定你希望如何構建它。就目前而言,您可以對此樹的創建進行硬編碼,但這不是一個通用的解決方案。 – Enigmativity 2012-08-06 04:38:00