0

検索ツリーのすべてのエントリをリストに書き込もうとしています。変更されていない順序で、子の前にノード。しかし、途中で順番を間違えてしまいます。

def n(value, children=[]):
    return [value,children]

#I want to keep this order in the list
tree = (n(5,[n(2,[n(3)]),n(6),n(8,[n(7),n(9)])]))

def is_empty(tree) :
    return tree == []

def to_list_iter(tree) :

    stack = []
    stack.append(tree)
    l = []
    while stack != [] :
        tree = stack.pop()
        if not is_empty(tree) :
            l.append(tree[0])
            n = len(tree[1])
            while n > 0:
                stack.append(tree[1][len(tree[1])-n])
                n -= 1

    return l

print (to_list_iter(tree))
# This will print the following output:
# [5, 8, 9, 7, 6, 2, 3]
# Instead of the desired [5, 2, 3, 6, 8, 7, 9]
4

1 に答える 1