How do I print out a tree structure?

前端 未结 8 1627
予麋鹿
予麋鹿 2020-11-27 12:42

I\'m trying to improve performance in our app. I\'ve got performance information in the form of a tree of calls, with the following node class:

public class         


        
8条回答
  •  时光说笑
    2020-11-27 13:29

    The trick is to pass a string as the indent and to treat the last child specially:

    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);
       }
    }
    

    If called like this:

    root.PrintPretty("", true);
    

    will output in this style:

    \-root
      \-child
        |-child
        \-child
          |-child
          |-child
          \-child
            |-child
            |-child
            | |-child
            | \-child
            |   |-child
            |   |-child
            |   |-child
            |   \-child
            |     \-child
            |       \-child
            \-child
              |-child
              |-child
              |-child
              | \-child
              \-child
                \-child
    

提交回复
热议问题