基本的に要求している出力はツリー構造です。つまり、入力を事前順序付けされた深さ優先トラバーサルとして扱い、一度にすべてをメモリに保持することなくツリー構造を読み取ることができます。
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])