2017-03-15 8 views
0

私は、左の枝、次にエントリ、そして最後に右の枝を訪問するように関数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 
+0

。 – tzaman

答えて

0

これはどう:あなたが再帰的に左右の枝に `flatten`を呼び出す必要が

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) 
関連する問題