title: How can I construct a tree using this data structure
body: <p>I have this tree structure, which a node may have multiple nodes.</p>
  
  <pre><code>public class Node
  {
      public Node()
      {
          ChildLocations = new HashSet&lt;Node&gt;();
      }
  
      public int Id { get; set; }
      public string Name { get; set; }
      public virtual int? ParentLocationId { get; set; }
      public virtual ICollection&lt;Node&gt; ChildLocations { get; set; }
  }
  </code></pre>
  
  <p>Now, I want to add a list of <code>parent-child</code> value into this structure. like:</p>
  
  <pre><code>{1,A} -&gt; {2,B}
  {1,A} -&gt; {3,C}
  {1,A} -&gt; {4,D}
  {3,C} -&gt; {5,E}
  {3,C} -&gt; {6,F}
  </code></pre>
  
  <p>to construct a tree looks like this:</p>
  
  <pre><code>          1A
          / |  \
      2B    3C   4D
           / \ 
         5E   6F
  </code></pre>
  
  <p>finally, it returns the <code>root</code> reference.</p>
  
  <p>I have come out this solution. But I have no confidence with recursive part. It this correct?</p>
  
  <pre><code>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);
          }
      }
  }
  </code></pre>