How do I print out a tree structure?

前端 未结 8 1608
予麋鹿
予麋鹿 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

    Create PrintNode method and use recursion:

    class Node
    {
        public string Name;
        public decimal Time;
        public List Children = new List();
    
        public void PrintNode(string prefix)
        {
            Console.WriteLine("{0} + {1} : {2}", prefix, this.Name, this.Time);
            foreach (Node n in Children)
                if (Children.IndexOf(n) == Children.Count - 1)
                    n.PrintNode(prefix + "    ");
                else
                    n.PrintNode(prefix + "   |");
        }
    }
    

    ANd then to print the whole tree just execute:

    topNode.PrintNode("");
    

    In my example it would give us something like that:

     + top : 123
       | + Node 1 : 29
       |   | + subnode 0 : 90
       |   |     + sdhasj : 232
       |   | + subnode 1 : 38
       |   | + subnode 2 : 49
       |   | + subnode 8 : 39
       |     + subnode 9 : 47
         + Node 2 : 51
           | + subnode 0 : 89
           |     + sdhasj : 232
           | + subnode 1 : 33
             + subnode 3 : 57
    

提交回复
热议问题