Make sure and check for cycles; the recursive code I've seen so far would be vulnerable to setting the "parent" of a category to some lower-level denizen. Track your "levels" as you visit the lineages, or simply note which categories have been visited, and hop out of the calls if you land in a familiar category.
Or is your graph guaranteed to be a tree with no cycles?
Matt