从二叉树构造字符串

Construct String from Binary Tree

计算科学的新手。

我在 Python 中掌握了二叉树的基础知识:

class TreeBinary:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

这对插入树很有效:

root = TreeBinary(1)
root.left = TreeBinary(2)
root.right = TreeBinary(3)
root.right.right = TreeBinary(4)

我试图发现的挑战之一是如何打印这棵树以显示子树(如果以下模型中有子树):

(1 (2 () ()) (3 () (4 () ())))
(2 () ())
(3 () (4 () ()))

我能够打印,但不能以这种格式打印,子树之间有这些空格:


def show_aux(root):
    if not root:
        return ''
    string = str(root.data)
    if root.left or root.right:
        string += '(' + show_aux(root.left) + ')'
    else:
        string += '('
        string += ')'
    if root.right:
        string += '(' + show_aux(root.right) + ')'
    else:
        string += '('
        string += ')'
    return string
def show(root):
    print('(' + show_aux(root) + ')')

我的结果是这样出来的:

(1(2()())(3()(4()())))
(2()())
(3()(4()()))

我想要一个方向,以预期的格式打印,子树之间有空格。

谢谢:)

像这样在每个 ( 前添加空格

def show_aux(root):
    if not root:
        return ''
    string = str(root.data)
    if root.left or root.right:
        string += ' (' + show_aux(root.left) + ')' #Space before '('
    else:
        string += ' (' #Space before '('
        string += ')'
    if root.right:
        string += ' (' + show_aux(root.right) + ')' #Space before '('
    else:
        string += ' (' #Space before '('
        string += ')'
    return string
def show(root):
    print('(' + show_aux(root) + ')')