How do I print out a tree structure?

本文分享了一种使用C#优雅地打印语法树结构的方法。通过递归遍历树节点并利用前缀来表示层级关系,实现了清晰直观的树形结构展示。文中提供了一个简洁的Node类实现及示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

How do I print out a tree structure?
http://stackoverflow.com/questions/1649027/how-do-i-print-out-a-tree-structure

多谢熊神给的链接,圆满的解决了我的问题。语法树本来自己写的丑的不忍直视。。现在好看多了,哈哈

其中最短小精悍的是节点中打印连线,很棒。
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(“”);
这是C#,都是C嘛。
mark 留念~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值