您请求的输出本质上是树结构。也就是说,您可以将您的输入视为预先排序的深度优先遍历并读取树结构,而无需一次将其全部保存在内存中:
depths = [0, 1, 2, 3, 2, 3, 3, 0, 1, 2, 1, 2] # Our input
next_id = 0 # Id of the next node
ids = [] # The ids of nodes as we traverse
parents = {} # Maps children to parents
children = {} # Maps parents to lists of children
for depth in depths
# First we give this node an id
id = next_id
next_id += 1
if ids.length <= depth
# If this is our first time to this depth, push a new level onto ids.
ids.append(id)
else
# Otherwise just insert the id into the list at its depth
ids[depth] = id
# And truncate off all elements after. This preserves the invariant
# that each id is the descendent of ids that appears before it.
ids[depth].resize(depth + 1)
assert(ids.length == depth + 1)
# Emit the link between this node and its parent
if depth > 0
parents[ids[depth]] = ids[depth - 1]
children[ids[depth - 1]] ||= [] # add the empty list first if needed
children[ids[depth - 1]].append(ids[depth])