简体   繁体   中英

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)

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.

ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM