Ultimate Parent Company (tree traversal)
viaGlassdoor
You are given a mapping of company → its direct parent company. Design a class to store this hierarchy and implement a function that, for any given company, returns its topmost (ultimate) parent — i.e. follow the parent links up the tree until you reach a company with no parent. This is a two-part question: first implement the class to hold the relationships, then implement the traversal.
Example:
parents = { "A": "B", "B": "C", "C": null, "D": "C" }
topMostParent("A") -> "C"
topMostParent("D") -> "C"
topMostParent("C") -> "C"
asked …