Convert a hierarchy from flat to nested representation.