Tree data structure in C#

前端 未结 20 2148
梦如初夏
梦如初夏 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 08:58

    If you would like to write your own, you can start with this six-part document detailing effective usage of C# 2.0 data structures and how to go about analyzing your implementation of data structures in C#. Each article has examples and an installer with samples you can follow along with.

    “An Extensive Examination of Data Structures Using C# 2.0” by Scott Mitchell

    0 讨论(0)
  • 2020-11-22 09:00

    I am surprised nobody mentioned the possibility to use XML with Linq :

    https://docs.microsoft.com/fr-fr/dotnet/standard/linq/create-xml-trees

    XML is the most mature and flexible solution when it comes to using trees and Linq provides you with all the tools that you need. The configuration of your tree also gets much cleaner and user-friendly as you can simply use an XML file for the initialization.

    If you need to work with objects, you can use XML serialization :

    https://docs.microsoft.com/fr-fr/dotnet/standard/serialization/introducing-xml-serialization

    0 讨论(0)
  • 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<T> where T : GenericTree<T> // recursive constraint  
    {
      // no specific data declaration  
    
      protected List<T> children;
    
      public GenericTree()
      {
        this.children = new List<T>();
      }
    
      public virtual void AddChild(T newChild)
      {
        this.children.Add(newChild);
      }
    
      public void Traverse(Action<int, T> visitor)
      {
        this.traverse(0, visitor);
      }
    
      protected virtual void traverse(int depth, Action<int, T> visitor)
      {
        visitor(depth, (T)this);
        foreach (T child in this.children)
          child.traverse(depth + 1, visitor);
      }
    }
    
    public class GenericTreeNext : GenericTree<GenericTreeNext> // 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);  
    }  
    
    0 讨论(0)
  • 2020-11-22 09:01

    I create a Node class that could be helpfull for other people. The class has properties like:

    • Children
    • Ancestors
    • Descendants
    • Siblings
    • Level of the node
    • Parent
    • Root
    • Etc.

    There is also the possibility to convert a flat list of items with an Id and a ParentId to a tree. The nodes holds a reference to both the children and the parent, so that makes iterating nodes quite fast.

    0 讨论(0)
  • 2020-11-22 09:01

    I've completed the code that @Berezh has shared.

      public class TreeNode<T> : IEnumerable<TreeNode<T>>
        {
    
            public T Data { get; set; }
            public TreeNode<T> Parent { get; set; }
            public ICollection<TreeNode<T>> Children { get; set; }
    
            public TreeNode(T data)
            {
                this.Data = data;
                this.Children = new LinkedList<TreeNode<T>>();
            }
    
            public TreeNode<T> AddChild(T child)
            {
                TreeNode<T> childNode = new TreeNode<T>(child) { Parent = this };
                this.Children.Add(childNode);
                return childNode;
            }
    
            public IEnumerator<TreeNode<T>> GetEnumerator()
            {
                throw new NotImplementedException();
            }
    
            IEnumerator IEnumerable.GetEnumerator()
            {
                return (IEnumerator)GetEnumerator();
            }
        }
        public class TreeNodeEnum<T> : IEnumerator<TreeNode<T>>
        {
    
            int position = -1;
            public List<TreeNode<T>> Nodes { get; set; }
    
            public TreeNode<T> Current
            {
                get
                {
                    try
                    {
                        return Nodes[position];
                    }
                    catch (IndexOutOfRangeException)
                    {
                        throw new InvalidOperationException();
                    }
                }
            }
    
    
            object IEnumerator.Current
            {
                get
                {
                    return Current;
                }
            }
    
    
            public TreeNodeEnum(List<TreeNode<T>> nodes)
            {
                Nodes = nodes;
            }
    
            public void Dispose()
            {
            }
    
            public bool MoveNext()
            {
                position++;
                return (position < Nodes.Count);
            }
    
            public void Reset()
            {
                position = -1;
            }
        }
    
    0 讨论(0)
  • 2020-11-22 09:02

    See http://quickgraph.codeplex.com/

    QuickGraph provides generic directed/undirected graph datastructures and algorithms for .Net 2.0 and up. QuickGraph comes with algorithms such as depth first seach, breath first search, A* search, shortest path, k-shortest path, maximum flow, minimum spanning tree, least common ancestors, etc... QuickGraph supports MSAGL, GLEE, and Graphviz to render the graphs, serialization to GraphML, etc...

    0 讨论(0)
提交回复
热议问题