中序遍历表示

Inorder Traversal representation

我正在为我的二叉搜索树进行中序遍历,我想知道是否有任何方法可以在同一行中打印出我的中序遍历的内容。

因此,例如,假设我希望它以 [-1, 1, 3, 6, 8, 10, 14, 90] 的形式出现,而不是它实际上是如何一个接一个地显示的。只是想办法让结果看起来更好。如果您有任何建议,请告诉我。我尝试了一些东西,但它们似乎不起作用。

def __in_order(self, root):
    if root == None:
        return
    else:
        self.__in_order(root.left_child)
        print(str(root.value))
        self.__in_order(root.right_child)

使用 yieldyield from 按顺序延迟生成值。

class Tree:
    def in_order(self):
        if self.__root:
            yield from self.__in_order(self.__root)

    def __in_order(self, root):
        if root:
            yield from self.__in_order(root.left_child)
            yield str(root.value)
            yield from self.__in_order(root.right_child)

然后您可以使用 list 将所有生成的值转换为列表并打印出来。

print(list(tree.in_order()))

yield from 是 python 3.3 或更高。如果您使用的是较低版本,则可以只使用循环和 yield 每个值。

for v in self.__in_order(root.left_child):
    yield v