如何以格式良好的方式打印一棵树?
在树结构中打印树的最简单方法是什么?比如……
some root
/ | \
child1 child2 child 3
/
anotherchild / \
yup another
即使是手动格式化也很难。如何让程序以这种方式打印一棵树?
What is the easiest way to print out a tree in it's tree-structure? Such as...
some root
/ | \
child1 child2 child 3
/
anotherchild / \
yup another
Even formatting it by hand is hard. How can you make a program print a tree this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
除非有一些不错的图形库可供您使用,否则您将在以您描述的方式表示层次结构时遇到很多麻烦。
假设您想将其打印到控制台或文件,您将不得不预先计算整个树中所有数据元素的长度,以便将它们正确排列。你如何处理像换行这样的事情?
更好的方法是垂直表示树,使用缩进来显示子元素。
这更容易编码,并且更能容忍换行之类的事情 - 因为一行上只有一个元素。这就是文件夹浏览器或 xml 文档显示其分层数据的方式。
为此,您需要进行深度优先遍历,并在递归步骤之前打印出节点:
希望有帮助
Unless there is some nice graphical library that you can use, you will have a lot of trouble representing a hierarchy in the way that you describe.
Assuming you want to print it to the Console, or a file, you will have to contend with pre-calculating the lengths of all of the data elements in the entire tree in order to line them up correctly. And how do you handle things like line-wrap?
A much better way is to represent the tree vertically, using indentation to show a child element.
This is much simpler to code, and more tolerant of things like linewrap - as there is only ever one element on a line. This is how a folder-browser or xml document might display its hierarchical data.
To do it this way, you do a depth-first traversal and before the recursive step you print out the node:
Hope that helps
以下答案是用 java 编写的,但它非常简单,可以轻松地转录为其他语言:
它会产生以下输出:
...如果您使用以下示例程序调用它:
The following answer is in java, but it is so simple that it can easily be transcribed to other languages:
It produces the following output:
...if you invoke it using the following sample program:
好吧,你可以尝试类似 PHP 的 var_dump - 如果你在树状数组上尝试 var_dump,它会给你一个该树的公平表示,即:
Well, you could try something like PHP's var_dump - if you try var_dump on a tree-like array, it will give you a fair representation of that tree, that is:
虽然我自己没有尝试过,graphviz 有一个纯文本输出格式。
Though I didn't try it myself, graphviz has a plain text output format.
对于类似问题,这个答案怎么样? ?
它打印出一棵漂亮的 ASCII 艺术树。
或者如果您愿意的话,也许这个完全图形化吗?
How about this answer to a similar question?
It prints a nice ASCII-art tree.
Or maybe this one if you want to go fully graphical?
去年我不得不这样做,编写一个家谱应用程序。在网上找到了一个java教程,它对我有帮助,但今天我的Google-fu失败了,所以我不得不简单地解释一下。
它只是一种基于子节点调整父节点位置的递归算法。在伪代码中,它是这样的:
我可能没有正确记住这一点,您可能需要稍微调整代码才能使其正确。
I had to do this last year writing a family tree application. Found a java tutorial online that helped but my Google-fu failed me today so I will have to simply explain it.
It is simply a recursive algorithm that adjusts position of parent node based on child nodes. In pseudocode it is something like this:
I may not be remembering this correctly, you may need to tweak the code a bit to get it right.