Pre-order alone loses the shape: both trees write A, B, C. Write each node with its number of children, in pre-order, and the shape comes back. Reading uses a stack of nodes still waiting for children:
def write_tree(children, top):
out, stack = [], [top]
while stack:
node = stack.pop()
out.append((node, len(children[node])))
# left to right
stack.extend(reversed(children[node]))
return out
def read_tree(records):
# waiting: [node, children still to come]
children, waiting = {}, []
for name, count in records:
children[name] = []
if waiting:
children[waiting[-1][0]].append(name)
waiting[-1][1] -= 1
if waiting[-1][1] == 0:
waiting.pop()
if count:
waiting.append([name, count])
return children, records[0][0]
records = write_tree(children, "Europe")
print(records[:4])
back, top = read_tree(records)
print(top, len(back), all(back[region] == children[region] for region in back))
[('Europe', 2), ('Portugal', 2), ('Lisbon District', 3), ('Lisbon', 0)]
Europe 13 True