Recursively traverse and build a nested dictionary of relationships