如何打印二叉树图?
我如何在java中打印一棵二叉树,以便输出如下:
cat
/\
cat1 cat2
值可以是多个字符。
How can i print a binary tree in java so that the output is like:
cat
/\
cat1 cat2
the values can be more than one character.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我通常使用 graphviz 中的 dot 程序来实现此目的。有一个简单的在线演示。这样您就不必担心间距或字体宽度。
I usually use the dot program from graphviz for this. There is an easy online demo of it. This way you don't have to worry about spacing or font widths.
二叉树由
组成。要打印这样一棵树,我们需要将左子树和右子树一个挨一个地打印(至少有一个空格),然后在其上打印根节点,以两个子树的中间为中心,并用 ASCII 线连接。为此,我们需要知道两个子树的宽度。
使用这些想法和递归来创建您的树图。
下面是一个可能有用的方法规范:
要输出树,您只需执行以下操作:
那么,我们如何实现
drawTree
方法呢?祝你好运!
A binary tree consists of
To print such a tree, we want to print the left and right subtrees one besides the other (with at least one space), and then print the root node over it, centered over the middle of both subtrees, and connected with ASCII lines. For this to work, we need to know how wide both subtrees are.
Use these ideas and recursion to create your tree-drawing.
Here is a method specification which may be useful:
To output the tree, you then only have to do this:
So, how could we implement our
drawTree
method?Good luck!
这是一个完整的、可运行的 Demo,它是 Scala 代码的匆忙翻译,因此它不是惯用的 Java。
有两种实现,一种采用 Tree 并从中生成 JTree,另一种使用 drawString 并使 Tree 适合 JFrame 大小。
打印树当然需要一些调整,因为您的节点可能没有公共属性 l、r 和 t,但您应该能够将它们转换为 left () 或 setLeft ()/getLeft () 等。
我不记得 ColorSwingPrinter 从哪里得名 - 它应该命名为 ResizingCanvasPrinter 或类似的名称。对不起。
这是两种实现的屏幕截图:
将较长的文本(如 cat、cat1、cat2)居中需要调整。到现在为止,第一个字符已放置在后代的中心
Here is a complete, runnable Demo, which is a rush translation from Scala code, so it isn't idiomatic Java.
There are two implementations, one which takes a Tree and produces a JTree from it, another one which uses drawString and fits the Tree to the JFrame size.
Printing your Tree needs of course some adaption, since your Nodes will probably not have public attributes l, r and t, but you should be able to translate them to left () or setLeft ()/getLeft () and so on.
I don't remember where ColorSwingPrinter got it's name from - it should be named ResizingCanvasPrinter or something like that. I'm sorry.
Here is a screenshot of both implementations:
Centering longer texts like cat, cat1, cat2 will need adjustment. By now, the first character is placed at the center of the descendants