简体   繁体   中英

Flattening a binary search tree

I want to define a function flatten(tree) such that it visits the left branch, and then entry, and then finally the right branch.

I've tried:

def flatten(tree):
    if is_empty_tree(tree):
        return tree
    else:
        return [left_branch(tree)]+[entry(tree)]+[right_branch(tree)]

but this isn't anywhere near to my desired output.

When tree is [5, [2, [1, [], []], []], [7, [6, [], []], [10, [], []]]] I'm supposed to get [1, 2, 3, 5, 6, 7, 10] but I got [[2, [1, [], []], []], 5, [7, [6, [], []], [10, [], []]]] instead.

How can I implement this function such that it visits the left branch, entry, and then the right branch and get the list that I want?

I have the following functions defined:

def build_tree(entry, left, right):
    return [entry, left, right]

def entry(tree):
    return tree[0]

def left_branch(tree):
    return tree[1]

def right_branch(tree):
    return tree[2]

def is_empty_tree(tree):
    if tree==[]:
        return True
    else:
        return False

How about this:

tree = [5, [2, [1, [], []], []], [7, [6, [], []], [10, [], []]]]

def flatten(tree):
    """Return a flattened list with all tree elements in order.

    tree is a list / tuple with either 0 elements (an empty tree) or at 
    least 3 elements. The first element is the value of the node, the 
    second the left (smaller) branch (another tree), and the
    right the bigger branch.

    E.g:

        tree = [5, [2, [1, [], []], []], [7, [6, [], []], [10, [], []]]]

    returns

        [1, 2, 5, 6, 7, 10]
    """
    if not tree:
        return []
    return flatten(tree[1]) + [tree[0]] + flatten(tree[2])

print flatten(tree)

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