我在 this SO question 找到了树的实现.不幸的是我不知道如何使用它。我还对其进行了更改,因为 LinkedList 没有 Add 方法:
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);
}
}
我有一个名为 tTable 的类,我想将它的子级和他们的孙级 (...) 存储在这棵树中。我的需要是找到直接的 child 而不是遍历整棵树。我可能还需要找到符合某些标准的 child 。假设 tTable 只有名字,我想找到名字符合某些条件的 child 。 tTables 构造函数根据 int 值(以某种方式)为名称赋予一个值。
如果我有这样的代码,我该如何使用 Traverse(编写委托(delegate));
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++));
最佳答案
此代码将遍历树并添加与给定名称匹配的所有节点。这是 C# 3x,对于 2.0,您需要使用匿名委托(delegate)。
NTree<tTable> tree = new NTree<tTable>(table);
string nameToMatch = "SomeName";
LinkedList<tTable> matches = new LinkedList<tTable>();
tree.Traverse(tree, data => {
if (data.Name == nameToMatch) {
matches.AddLast(data);
}
});
关于c# - 如何在C#中使用树数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2538263/