Tree data structure in C#

前端 未结 20 2190
梦如初夏
梦如初夏 2020-11-22 08:30

I was looking for a tree or graph data structure in C# but I guess there isn\'t one provided. An Extensive Examination of Data Structures Using C# 2.0 explains a bit about w

20条回答
  •  难免孤独
    2020-11-22 09:01

    I have a little extension to the solutions.

    Using a recursive generic declaration and a deriving subclass you can better concentrate on your actual target.

    Notice, it's different from a non generic implementation, you don`t need to cast 'node' in 'NodeWorker'.

    Here's my example:

    public class GenericTree where T : GenericTree // recursive constraint  
    {
      // no specific data declaration  
    
      protected List children;
    
      public GenericTree()
      {
        this.children = new List();
      }
    
      public virtual void AddChild(T newChild)
      {
        this.children.Add(newChild);
      }
    
      public void Traverse(Action visitor)
      {
        this.traverse(0, visitor);
      }
    
      protected virtual void traverse(int depth, Action visitor)
      {
        visitor(depth, (T)this);
        foreach (T child in this.children)
          child.traverse(depth + 1, visitor);
      }
    }
    
    public class GenericTreeNext : GenericTree // concrete derivation
    {
      public string Name {get; set;} // user-data example
    
      public GenericTreeNext(string name)
      {
        this.Name = name;
      }
    }
    
    static void Main(string[] args)  
    {  
      GenericTreeNext tree = new GenericTreeNext("Main-Harry");  
      tree.AddChild(new GenericTreeNext("Main-Sub-Willy"));  
      GenericTreeNext inter = new GenericTreeNext("Main-Inter-Willy");  
      inter.AddChild(new GenericTreeNext("Inter-Sub-Tom"));  
      inter.AddChild(new GenericTreeNext("Inter-Sub-Magda"));  
      tree.AddChild(inter);  
      tree.AddChild(new GenericTreeNext("Main-Sub-Chantal"));  
      tree.Traverse(NodeWorker);  
    }  
    
    static void NodeWorker(int depth, GenericTreeNext node)  
    {                                // a little one-line string-concatenation (n-times)
      Console.WriteLine("{0}{1}: {2}", String.Join("   ", new string[depth + 1]), depth, node.Name);  
    }  
    

提交回复
热议问题