Implementing Tree

  • Thread starter csharpula csharp
  • Start date
C

csharpula csharp

Hello ,
I would like to build a tree structure in c# using the arraylist or hash
table. what is the best way to implement it if I want to add children
and to print my tree.
Thank you!
 
J

Jon Skeet [C# MVP]

I would like to build a tree structure in c# using the arraylist or hash
table. what is the best way to implement it if I want to add children
and to print my tree.

Well, how far have you got? Where are you stuck?

Jon
 
K

KWienhold

I don't know how to start implementing. Need to find good design?

*** Sent via Developersdexhttp://www.developersdex.com***

I guess the basic implementation would be a Node class that contains a
List<Node> or Hashtable<string, Node> (if you have a unique key for
every node under a given parent).
Using this sort of implementation gives you a hierarchy of nodes, so
that ever node can be the parent of further nodes, just what a tree
is.
However its may still be a long way to go from there to any actually
useful implementation, depending on your needs.

hth,
Kevin Wienhold
 
G

Gord Tanner

Here is a quick start:

that is the basics of a tree collection. Notice that the children are
not exposed as a mutable object since you want to control the add and
remove to update the parent.

public class Node<T>
{
private Node<T> _parent;
private List<Node<T>> _children;

public IEnumerable<Node<T>> Children
{
get { return _children; }
}

public Node<T> Parent
{
get{return _parent;}
}

public Node()
{
_children = new List<Node<T>>();
}

public void Add(Node<T> child)
{
_children.Add(child);
child.SetParent(this);
}

public void Remove(Node<T> child)
{
child.SetParent(null);
_children.Remove(child);
}

private void SetParent(Node<T> parent)
{
_parent = parent;
}
}

This should give you a good start though.

Gord
 
D

Doug Semler

csharpula csharp said:
Hello ,
I would like to build a tree structure in c# using the arraylist or hash
table. what is the best way to implement it if I want to add children
and to print my tree.
Thank you!


Hierarchical Tree? AVL Tree? B-Tree (or its varients B* Tree or B+ Tree)?
Splay Tree?

All of these are well known structures with well defined behavior that can
be found out on the net and "converted" to C#...


(obligitory back-to-school joke:)

If you gave us the exact wording of your homework assignment <g>....

--
Doug Semler, MCPD
a.a. #705, BAAWA. EAC Guardian of the Horn of the IPU (pbuhh).
The answer is 42; DNRC o-
Gur Hfrarg unf orpbzr fb shyy bs penc gurfr qnlf, abbar rira
erpbtavmrf fvzcyr guvatf yvxr ebg13 nalzber. Fnq, vfa'g vg?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top