How do I print out a tree structure?

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

    This is a generic version of Joshua Stachowski's answer. The good thing about Joshua Stachowski's answer is that it doesn't require the actual node class to implement any extra method and it looks nice as well.

    I made his solution generic which can be used for any type without modifying the code.

        public static void PrintTree(T rootNode,
                                        Func nodeLabel, 
                                        Func> childernOf)
                {
                    var firstStack = new List();
                    firstStack.Add(rootNode);
    
                    var childListStack = new List>();
                    childListStack.Add(firstStack);
    
                    while (childListStack.Count > 0)
                    {
                        List childStack = childListStack[childListStack.Count - 1];
    
                        if (childStack.Count == 0)
                        {
                            childListStack.RemoveAt(childListStack.Count - 1);
                        }
                        else
                        {
                            rootNode = childStack[0];
                            childStack.RemoveAt(0);
    
                            string indent = "";
                            for (int i = 0; i < childListStack.Count - 1; i++)
                            {
                                indent += (childListStack[i].Count > 0) ? "|  " : "   ";
                            }
    
                            Console.WriteLine(indent + "+- " + nodeLabel(rootNode));
                            var children = childernOf(rootNode);
                            if (children.Count > 0)
                            {
                                childListStack.Add(new List(children));
                            }
                        }
                    }
                }
    

    Usage

     PrintTree(rootNode, x => x.ToString(), x => x.Children);
    

提交回复
热议问题