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

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

问题描述

我正在努力提高我们应用的性能.我以调用树的形式获得了性能信息,具有以下节点类:

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

我想打印出树,以便我可以看到节点之间的线条 - 类似于 这个问题.我可以在 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天全站免登陆