Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What collection to store a tree structure?

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.

LinkedList only provides adding one node to another node, if I understand it correctly.

I have looked at C5 treeset collection, but it doesn't seem to have Add() method to add more than 2 nodes to one node.

I have also looked at Treeview class from Windows Forms library, but I do not want to add Windows forms dll to my project, since I am building a service layer application. (or is it fine?)

I do not want to write my own tree collection class, if there is already one provided by 3rd party?

Any suggestion please?

Thanks

like image 724
gunnerz Avatar asked Aug 08 '12 15:08

gunnerz


People also ask

Which database is best for tree structure?

MongoDB allows various ways to use tree data structures to model large hierarchical or nested data relationships. Presents a data model that organizes documents in a tree-like structure by storing references to "parent" nodes in "child" nodes.

How is a tree stored?

The table below represents a tree stored in a computer's memory. Each node of the tree contains three cells. The first cell contains the data to be stored; the second cell contains a pointer to the first cell's left child, and the third cell contains a pointer to the first cell's right child.

How trees are stored in database?

The standard method of storing hierarchical data is simple parent-child relationship. Each record in the database includes a —parent id—, and a recursive query through the records build the children, siblings, and levels of the tree.

What is a tree structure in computer?

A tree or tree structure is a hierarchical data structure that organizes data elements, called nodes, by connecting them with links, called branches. This structure is used to help display large amounts of information in an easy to read format.


1 Answers

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");
like image 200
cellik Avatar answered Sep 20 '22 18:09

cellik