2012-08-06 66 views
-1

我有這樣的樹結構,其中,節點可以具有多個節點構造的樹。我怎樣才能使用這種數據結構

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); 
     } 
    } 
} 
+0

我會說它..「你有什麼嘗試?」 – 2012-08-06 04:21:08

+0

你似乎有這個課程?你需要什麼具體的幫助?使用遞歸實現一個添加函數來查找父節點應該很容易。 – nunespascal 2012-08-06 04:29:36

+0

我認爲你需要指定你希望如何構建它。就目前而言,您可以對此樹的創建進行硬編碼,但這不是一個通用的解決方案。 – Enigmativity 2012-08-06 04:38:00

回答

0

按我給你的問題的評論,這部作品打造您所需要的樹:

public Node BuildTree() 
{ 
    var _1A = new Node() { Id = 1, Name = "A", }; 
    var _2B = new Node() { Id = 2, Name = "B", }; 
    var _3C = new Node() { Id = 3, Name = "C", }; 
    var _4D = new Node() { Id = 4, Name = "D", }; 
    var _5E = new Node() { Id = 5, Name = "E", }; 
    var _6F = new Node() { Id = 6, Name = "F", }; 
    _1A.ChildLocations.Add(_2B); 
    _1A.ChildLocations.Add(_3C); 
    _1A.ChildLocations.Add(_4D); 
    _3C.ChildLocations.Add(_5E); 
    _3C.ChildLocations.Add(_6F); 
    return _1A; 
} 

但它不是很通用。你能詳細說明你的需求嗎?

+0

我正在尋找一個不硬編碼的解決方案。我編輯了我的帖子,我不確定我的遞歸方法。 – Timeless 2012-08-06 09:44:29

+0

@null - 這是我的預期 - 我希望我的回答能夠帶來這個問題的更新。 :-) – Enigmativity 2012-08-07 02:55:37