• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2028
  • Last Modified:

build a tree using c#

I am hoping that someone can help me on how to build a tree using c#
My basic need is to be able to
1. Define a tree
2. Define a parent node
3. Define children of that parent
4. Create children of a child node.

Consider all the nodes to just be letters
I am trying to build a tree to search for prefix, for example if the prefix is "un" then the parent is "u" and the child is "n".

Can anyone help me with this?

Consider also the following example (maybe it will help?)

Parent / Child /Child
A / B / C
A / C
A / D
B / E
B / F
C / F
C / G

Thanks in advance for any help

2 Solutions

I would say the best way to implement a tree concept in .NET is to follow the composite design pattern. This pattern is the crux behing the tree concept and could be used for traversing the tree as well. The best reading for this is at

So my feeling is in addition to Display you can have method like Search childern and returns a list of Nodes. This propogration works out well. The treeview in .NET I guess as well as Explorer in Windows follows the same concept.

I'm not sure I understand exactly what you're looking for, but here's the basic code for a tree:
    public class TreeElement
        private List<TreeElement> _children = new List<TreeElement>();
        private string _letter;
        public List<TreeElement> Children
            get { return _children; }
        public string Letter
            get { return _letter; }
        public bool HasChildren
            get { return (_children.Count > 0); }
        public TreeElement(string letter)
            _letter = letter;
//In another file:
public void TreeTest()
            TreeElement parent = new TreeElement("A");
            TreeElement child = new TreeElement("B");
            TreeElement grandchild = new TreeElement("C");
        private void WriteChildren(TreeElement element)
            //write this element
            //now write the children
            if (element.HasChildren)
                foreach(TreeElement child in element.Children)

Open in new window

suzan_Author Commented:
thanks all for help
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now