# L-13 MCS 275 Wed 8 Feb 2017 : treesort.py
"""
We create a tree of lists to sort integer numbers.
The tree is a recursive triple of triplets.
"""

def add(tree, nbr):
    """
    Adds a number nbr to the triple of triples.
    All numbers less than tree[1] are in tree[0].
    All numbers greater than or equal to tree[1]
    are in tree[2].  Returns the new tree.
    """
    if len(tree) == 0:
        return ((), nbr, ())
    elif nbr < tree[1]:
        return (add(tree[0], nbr), tree[1], tree[2])
    else:
        return (tree[0], tree[1], add(tree[2], nbr))

def flatten(tree):
    """
    tree is a recursive triple of triplets.
    Returns a list of all numbers in tree
    going first along the left of tree, before
    the data at the node and the right of tree.
    """
    if len(tree) == 0:
        return []
    else:
        result = flatten(tree[0])
        result.append(tree[1])
        result = result + flatten(tree[2])
        return result

def is_in(tree, nbr):
    """
    Returns True if nbr belongs to the tree,
    returns False otherwise.
    """
    if len(tree) == 0:
        return False
    elif tree[1] == nbr:
        return True
    elif nbr < tree[1]:
        return is_in(tree[0], nbr)
    else:
        return is_in(tree[2], nbr)

def main():
    """
    Prompts the user for numbers and sorts
    using a tree: a triple of triplets.
    """
    tree = ()
    while True:
        nbr = int(input('give a number (-1 to stop) : '))
        if nbr < 0:
            break
        if is_in(tree, nbr):
            print(nbr, 'is already in the tree')
        else:
            tree = add(tree, nbr)
        print('T =', tree)
    print('sorted numbers =', flatten(tree))

main()
