我正在尝试提高我们应用程序的性能。我获得了调用树形式的性能信息,具有以下节点类:
public class Node
{
public string Name; // method name
public decimal Time; // time spent in method
public List<Node> Children;
}
我想打印出树,这样我就可以看到节点之间的线 - 类似于 this question 中的内容.我可以在 C# 中使用什么算法来做到这一点?
编辑:显然我需要使用递归 - 但我的尝试总是将行放在错误的位置。我要的是一种特定的算法,它将以一种很好的方式打印树 - 何时打印垂直线以及何时打印水平线的详细信息。
编辑:仅使用字符串的副本来缩进节点是不够的。我不是在找
A
|-B
|-|-C
|-|-D
|-|-|-E
|-F
|-|-G
必须是
A
+-B
| +-C
| +-D
| +-E
+-F
+-G
或任何类似的东西,只要树结构是可见的。请注意,C 和 D 的缩进方式与 G 不同——我不能只使用重复的字符串来缩进节点。
最佳答案
诀窍是传递一个字符串作为缩进并特殊对待最后一个 child :
class Node
{
public void PrintPretty(string indent, bool last)
{
Console.Write(indent);
if (last)
{
Console.Write("\\-");
indent += " ";
}
else
{
Console.Write("|-");
indent += "| ";
}
Console.WriteLine(Name);
for (int i = 0; i < Children.Count; i++)
Children[i].PrintPretty(indent, i == Children.Count - 1);
}
}
如果这样调用:
root.PrintPretty("", true);
将以这种风格输出:
\-root
\-child
|-child
\-child
|-child
|-child
\-child
|-child
|-child
| |-child
| \-child
| |-child
| |-child
| |-child
| \-child
| \-child
| \-child
\-child
|-child
|-child
|-child
| \-child
\-child
\-child
关于c# - 如何打印出树结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1649027/