pythonbinary-search-treetrailing-whitespace

Can't work out how to remove the trailing whitespace from my result


My code finds the input for a balanced binary tree from an array.

array = [178, 57, 26, 157, 679, 397, 898]

def myFunc(x):
    for i in range(1, len(x)):
        inp = x[i]
        j=i-1
        while j>=0 and inp<x[j]:
            x[j+1] = x[j]
            j-=1
        x[j+1] = inp
    x

    class tn(object):
        def __init__(self, y):
            self.val = y
            self.left = None
            self.right =None

    def sort2bst(x):
        if not x:
            return None
        m = len(x)//2
        node = tn(x[m])
        node.left = sort2bst(x[:m])
        node.right  = sort2bst(x[m+1:])
        return node


    def po(node):
        if not node:
            return
        print(node.val, end=" ")
        po(node.left)
        po(node.right)

    result = sort2bst(x)
    po(result)

myFunc(array)

The output looks like this: 178 57 26 157 679 397 898

So far, I've been able to do everything except removing the trailing whitespace from the output. I have to use end=" " for it to output in a single line, but this means the last value also has an empty space after it. I tried to use .rstrip() but that's also not working because I think it only works on strings. How would I remove this whitespace at the end?


Solution

  • Instead of continuously printing, you can collect the results and create the string once you have them all:

    def po(node):
        if not node:
            return []
        return [str(node.val), *po(node.left), *po(node.right)]
    
    result = sort2bst(x)
    print(" ".join(po(result)))