c# - 如何打印出树结构?

标签 c# .net tree pretty-print

我正在尝试提高我们应用程序的性能。我获得了调用树形式的性能信息,具有以下节点类:

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/

相关文章:

c++ - 使用尾递归访问树或图形结构

c - 在C二叉树中插入函数?

c# - MSBuild 中出现错误 CS0840,但 VS2015 中没有错误

.net 文本分隔库?

c# - 查找两个树结构 C# 之间的差异

c# - 将 MongoDB Json 转换为 C# 类

c# - 在 C# 程序中,程序什么时候结束执行?

c# - Web API 2 路由属性在一个 Controller 中起作用,但在另一个 Controller 中不起作用

c# - 如何安全地处理 AES “Key” 和 “IV” 值

c# - 注册后将用户详细信息输入数据库