0

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)
nessa.c
  • 17
  • 4
  • instead of print use `yield` and for your recursive calls use `yield from` (if py 3.3+) or just yield in a loop. You can then just use `print(list(tree.in_order()))` to display the elements. You would also have the option of lazily consuming the returned elements. – Paul Rooney Apr 06 '18 at 04:20
  • i have never used yield before. How does that work, if you don't mind me asking? – nessa.c Apr 06 '18 at 04:25
  • Hopefully [this](https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do) wont be too much of an intimidating introduction. [Here](https://ideone.com/AMnp9N) is what I mean. It's not runnable, because I'd have to implement the tree, but you might get the idea. – Paul Rooney Apr 06 '18 at 04:28
  • It worked! Thank you! – nessa.c Apr 06 '18 at 04:32

1 Answers1

0

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
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61