how to use a tree data structure in C#
- by matti
I found an implementation for a tree at this SO question. Unfortunately I don't know how to use it. Also I made a change to it since LinkedList does not have Add method:
delegate void TreeVisitor<T>(T nodeData);
class NTree<T>
{
T data;
List<NTree<T>> children;
public NTree(T data)
{
this.data = data;
children = new List<NTree<T>>();
}
public void AddChild(T data)
{
children.Add(new NTree<T>(data));
}
public NTree<T> GetChild(int i)
{
return children[i];
}
public void Traverse(NTree<T> node, TreeVisitor<T> visitor)
{
visitor(node.data);
foreach (NTree<T> kid in node.children)
Traverse(kid, visitor);
}
}
I have class named tTable and I want to store it's children and their grandchildren (...) in this tree. My need is to find immediate children and not traverse entire tree. I also might need to find children with some criteria. Let's say tTable has only name and I want to find children with names matching some criteria. tTables constructor gives name a value according to int-value (somehow).
How do I use Traverse (write delegate) if I have code like this;
int i = 0;
Dictionary<string, NTree<tTable>> tableTreeByRootTableName =
new Dictionary<string, NTree<tTable>>();
tTable aTable = new tTable(i++);
tableTreeByRootTableName[aTable.Name] = new NTree(aTable);
tableTreeByRootTableName[aTable.Name].AddChild(new tTable(i++));
tableTreeByRootTableName[aTable.Name].AddChild(new tTable(i++));
tableTreeByRootTableName[aTable.Name].GetChild(1).AddChild(new tTable(i++));