我正在尝试将搜索树的所有条目写入列表。以不变的顺序,子节点之前的节点。但我在途中的某个地方把订单混在一起了。
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]