繁体   English   中英

展平二叉搜索树

[英]Flattening a 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] 1,2,3,5,6,7,10 [1, 2, 3, 5, 6, 7, 10]但是我得到了[[2, [1, [], []], []], 5, [7, [6, [], []], [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

这个怎么样:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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