java 用Java打印二叉树

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16596904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:25:20  来源:igfitidea点击:

Printing a binary tree in Java

javaprintingbinary-treepseudocode

提问by thePurpleMonkey

I'm trying to implement a Binary Tree, and for ease of debugging, I want to be able to print the tree so it actually looks like a tree. For example:

我正在尝试实现一棵二叉树,为了便于调试,我希望能够打印树,使其实际上看起来像一棵树。例如:

              50
      42              71
  31      45      60      98
6    11 43  49  55

Or something similar. (The tree is always guaranteed to be complete.) I just need an algorithm or pseudocode to get me started. I just have no idea how implement something like this. Thanks for you help.

或者类似的东西。(树总是保证是完整的。)我只需要一个算法或伪代码来让我开始。我只是不知道如何实现这样的东西。谢谢你的帮助。

回答by Ric

What you have in the question is not exactly a Binary tree. A binary tree at each level has to have the left node smaller than the root and the right node greater that the root.

您在问题中所拥有的不完全是二叉树。每一层的二叉树的左节点必须小于根,右节点大于根。

It can be best implemented with recursion.

最好用递归来实现。

Try this linkfor sample code and explanation.

尝试此链接以获取示例代码和说明。

回答by monojohnny

I'll try and start this off: (Took the liberty of using Python 2.x rather than pseudo code).

我会尝试从这个开始:(冒昧地使用 Python 2.x 而不是伪代码)。

# Doesn't work yet.
# Assumes two characters ('42', '06' etc) per string representation of number.
# If not, alter the formatting %02d as appropriate.
global line_length
line_length=80
def pad(number_of_nodes):
        global line_length
        return "_"*(line_length/number_of_nodes)

def printlevel(nodes):
        global line_length
        padstring=pad(len(nodes))
        stringnodes=[ "%02d"%(n) for n in nodes ]
        leader="_"* abs( (line_length/2) - len(padstring) )
        print leader, padstring.join(stringnodes)


for level in [  [50],
                [42,71],
                [31,45,60,98],
                [6,11,43,49,55]
        ]:
        printlevel(level)

Since (I believe) the question is more one of formatting than actually visiting tree nodes...I have just flattened out the tree to a list of lists.. This actually doesn't work, but I think it can be re-arranged to get it working....

由于(我相信)问题更多是格式化而不是实际访问树节点......我刚刚将树展平为列表列表..这实际上不起作用,但我认为它可以重新排列让它工作......