Search code examples
pythonbinary-search-treeinorder

Inorder Traversal representation


I am working on an Inorder traversal for my binary search tree and I was wondering if there is any way to print out the content of my inorder traversal all in the same line.

So, for example, let's say I want it to come out as [ -1, 1, 3, 6, 8, 10, 14, 90] instead of how it actually does which if one by one. Just looking for ways to make the outcome look nicer. If you have any suggestions let me know. I have tried a few things but they don't seem to work.

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)

Solution

  • Use yield and yield from to lazily produce the values in order.

    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)
    

    You can then use list to convert all the yielded values into a list and print it.

    print(list(tree.in_order()))
    

    yield from is python 3.3 or greater. If you are on a lower version, you can just use a loop and yield each value.

    i.e

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