How do I print out a tree structure?

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

    With Recursion

    You'll need to keep track of an indentation string that's modified as you go deeper into the tree. To avoid adding extra | characters, you'll also need to know whether the Node is the last child in that set.

    public static void PrintTree(Node tree, String indent, Bool last)
    {
        Console.Write(indent + "+- " + tree.Name);
        indent += last ? "   " : "|  ";
    
        for (int i = 0; i < tree.Children.Count; i++)
        {
            PrintTree(tree.Children[i], indent, i == tree.Children.Count - 1);
        }
    }
    

    When called like this:

    PrintTree(node, "", true)
    

    It will output text like this:

    +- root
       +- branch-A
       |  +- sibling-X
       |  |  +- grandchild-A
       |  |  +- grandchild-B
       |  +- sibling-Y
       |  |  +- grandchild-C
       |  |  +- grandchild-D
       |  +- sibling-Z
       |     +- grandchild-E
       |     +- grandchild-F
       +- branch-B
          +- sibling-J
          +- sibling-K
    

    Without Recursion

    If you happen to have a very deep tree and your call stack size is limited, you can instead do a static, non-recursive tree traversal to output the same result:

    public static void PrintTree(Node tree)
    {
        List firstStack = new List();
        firstStack.Add(tree);
    
        List> 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
            {
                tree = childStack[0];
                childStack.RemoveAt(0);
    
                string indent = "";
                for (int i = 0; i < childListStack.Count - 1; i++)
                {
                    indent += (childListStack[i].Count > 0) ? "|  " : "   ";
                }
    
                Console.WriteLine(indent + "+- " + tree.Name);
    
                if (tree.Children.Count > 0)
                {
                    childListStack.Add(new List(tree.Children));
                }
            }
        }
    }
    

提交回复
热议问题