展平二叉搜索树

时间:2017-03-15 15:21:22

标签: python binary-tree binary-search-tree

我想定义一个函数flatten(tree),使其访问左分支,然后是条目,最后是右分支。

我试过了:

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

但这并不接近我想要的输出。

当树[5, [2, [1, [], []], []], [7, [6, [], []], [10, [], []]]]时,我应该[1, 2, 3, 5, 6, 7, 10],但我得到了[[2, [1, [], []], []], 5, [7, [6, [], []], [10, [], []]]]

如何实现此功能,使其访问左侧分支,条目,然后访问右侧分支并获取我想要的列表?

我定义了以下功能:

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

1 个答案:

答案 0 :(得分:0)

这个怎么样:

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)