What collection to store a tree structure?

后端 未结 1 1206
刺人心
刺人心 2020-12-18 23:13

I want to store an organisation chart in a collection. I think a tree data structure will be best suited to my needs, as I need to add multiple nodes to one node.

相关标签:
1条回答
  • 2020-12-18 23:27

    Something like this can be a starting point. By using generics this one can hold a tree of anything

    class TreeNode<T>
    {
        List<TreeNode<T>> Children = new List<TreeNode<T>>();
    
        T Item {get;set;}
    
        public TreeNode (T item)
        {
            Item = item;
        }
    
        public TreeNode<T> AddChild(T item)
        {
            TreeNode<T> nodeItem = new TreeNode<T>(item);
            Children.Add(nodeItem);
            return nodeItem;
        }
    }
    

    A sample which holds a tree of strings

    string root = "root";
    TreeNode<string> myTreeRoot = new TreeNode<string>(root);
    var first = myTreeRoot.AddChild("first child");
    var second = myTreeRoot.AddChild("second child");
    var grandChild = first.AddChild("first child's child");
    
    0 讨论(0)
提交回复
热议问题