如何打印出一个树状结构? [英] How do I print out a tree structure?

查看:1086
本文介绍了如何打印出一个树状结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想改善我们的应用程序的性能。我有在呼叫的树的形式表现的信息,具有下列节点类:

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 Node
{
    public string Name; // method name
    public decimal Time; // time spent in method
    public List<Node> Children;
}

我要打印出来的树,这样我可以看到在节点之间线 - 有点像在<一个href="http://stackoverflow.com/questions/1581559/ascii-library-for-creating-$p$ptty-directory-trees">this问题。什么是算法,我可以在C#中使用这样做?

I want to print out the tree such that I can see lines between the nodes - something like in this question. What's an algorithm I can use in C# for doing that?

编辑:很显然,我需要使用递归 - 但我尝试不断地将在错误的地方的线条。我要问的是一个特定的算法,将打印树在一个不错的方式 - 当打印一条垂直线,当打印横向的细节

Obviously I need to use recursion - but my attempts keep putting the lines in the wrong places. What I'm asking for is a specific algorithm that will print the tree in a nice manner - the details of when to print a vertical line and when to print a horizontal one.

编辑:这是不够的只是使用一个字符串拷贝到缩进的节点。我不是在寻找

It isn't sufficient just to use copies of a string to indent the nodes. I'm not looking for

A
|-B
|-|-C
|-|-D
|-|-|-E
|-F
|-|-G

它必须是

A
+-B
| +-C
| +-D
|   +-E
+-F
  +-G

或任何类似的,只要树结构是可见的。请注意,C和D都缩进不同,以G - 我不能只用一个重复的字符串缩进节点

or anything similar, so long as the tree structure is visible. Notice that C and D are indented differently to G - I can't just use a repeated string to indent the nodes.

推荐答案

关键是要传递一个字符串作为缩进和治疗的最后一个子特地:

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

如果这样调用:

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

这篇关于如何打印出一个树状结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆