我在c#中创建了一个基本的n-ary树:
树:
public class Tree<T>
{
private Node<T> root;
public Tree()
{
root = null;
}
public Node<T> Root
{
get
{
return root;
}
set
{
root = value;
}
}
public T search (T data)
{
return (root != null) ? raiz.search(data) : default(T);
}
}
节点:
public class Node<T>
{
private T data;
private List<Node<T>> childs;
public Node(T data)
{
this.data = data;
this.childs = null;
}
public T Data
{
get
{
return data;
}
set
{
data = value;
}
}
public List<NodoArbol<T>> Childs
{
get
{
return childs;
}
set
{
childs = value;
}
}
public void addChild(Node node)
{
if (child == null)
{
childs = new List<Node<T>>();
}
childs.Add(node);
}
public T search(T data)
{
if (this.data.Equals(data))
{
return this.data;
}else
{
for (int i = 0; i < childs.Count; i++)
{
T aux = childs.ElementAt(i).search(data);
if (aux != null)
{
return aux;
}
}
return default(T);
}
}
}
我喜欢树的直观表示,以便我可以快速测试以查看子节点是否在正确的位置并测试我的遍历(预订/按订单/后订单)这样的事情
答案 0 :(得分:1)
如果足以将其输出到控制台:
public void PrintTree(Node node, int indentSize, int currentLevel)
{
var currentNode = string.Format("{0}{1}", new string(" ",indentSize*currentLevel, node.Data);
Console.WriteLine(currentNode)
foreach(var child in node.Children)
{
PrintTree(child, indentSize, currentLevel+1);
}
}
然后像这样称呼它
PrintTree(yourTreeInstance.Root,4,0);
您也可以使用Debug.WriteLine输出到调试控制台而不是主控台