title: Example usage of a custom delegate in c#
body: <p>I found <a href="https://stackoverflow.com/questions/66893/tree-data-structure-in-c">this</a> question on SO about a tree implementation in C#. I have no idea about delegates and I was wondering how the following code could be used to implement a tree. Also, what would be the most efficient way to keep a track of parent nodes?</p>
  
  <pre><code>delegate void TreeVisitor&lt;T&gt;(T nodeData);
  
  class NTree&lt;T&gt;
  {
      T data;
      LinkedList&lt;NTree&lt;T&gt;&gt; children;
  
      public NTree(T data)
      {
          this.data = data;
          children = new LinkedList&lt;NTree&lt;T&gt;&gt;();
      }
  
      public void addChild(T data)
      {
          children.AddFirst(new NTree&lt;T&gt;(data));
      }
  
      public NTree&lt;T&gt; getChild(int i)
      {
          foreach (NTree&lt;T&gt; n in children)
              if (--i == 0) return n;
          return null;
      }
  
      public void traverse(NTree&lt;T&gt; node, TreeVisitor&lt;T&gt; visitor)
      {
          visitor(node.data);
          foreach (NTree&lt;T&gt; kid in node.children)
              traverse(kid, visitor);
      }        
  }
  </code></pre>